前面一篇文章,我們介紹了如何在c#中對數據庫進行更新操作。主要是利用SqlCommand 對象的ExecuteNonQuery方法。
這篇文章介紹,如何進行查詢操作。本文給出的例子仍然是針對sql server數據庫的。對於其它數據庫(源),區別只是引入的部門api的不同,但流程和方法是一樣的。
一、查詢單個值
SqlCommand 對象提供了一個ExecuteScalar方法,它的作用是返回查詢結果中第一條記錄中的第一列的值。如果查詢結果沒有記錄,則返回的值為null。
該方法往往用於檢查數據是否存在。
我們還是看例子:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace DbExample
{
class DbActor
{
public void querySingleValue()
{
SqlConnection conn = getConnection();
try
{
conn.Open();
SqlCommand command = new SqlCommand("select count(*) from userinfo", conn);
int value = (int)command.ExecuteScalar();
MessageBox.Show(value.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private SqlConnection getConnection()
{
string strConnection = @"Data Source = localhost\SQLEXPRESS; Initial Catalog = mydb; User Id = sa; Password = Xqh980234;";
SqlConnection conn = new SqlConnection(strConnection);
return conn;
}
}
}
二、遍歷所有記錄
在大部分場景下,我們需要獲取查詢結果的所有數據。這個需要用到c#的DataReader對象。我們看一個例子:
public void query()
{
SqlConnection conn = getConnection();
SqlDataReader reader = null;
try
{
conn.Open();
SqlCommand command = new SqlCommand("select * from userinfo", conn);
reader = command.ExecuteReader();
while (reader.Read())
{
string result = reader.GetString(0) + "," + reader.GetString(1);
MessageBox.Show(result);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (reader!=null)
reader.Close();
conn.Close();
}
}
對於查詢操作,基本上就是上面標准的格式,需要注意的地方是:
1)獲取字段是,序號是從0開始的(0代表第一個字段)。有的開發語言的api(如java)是從1開始的。
2)最後的SqlDataReader對象不要忘了關閉。不要要放到try語句的最後,要放到finally語句中,防止放在try最後但處理過程中出現異常而無法被調用。
3)如果主需要取一條記錄,把while改成if語句即可。
本篇文章介紹了,如何在c#中進行數據庫查詢操作,結合上篇文章對更新操作的介紹,基本上可以滿足大部分場景的開發。當然只是介紹最基本的使用方法和流程。還有一些細節的API需要自己去了解。在下面的文章中,我們將繼續介紹如何使用DataSet對象來訪問數據庫。