ExecuteReader()方法一般配合SqlDataReader對象使用,執行得到的數據集為只讀且光標只能從前向後移動,ExecuteReader返回一個SqlDataReader對象:
如:
string connString = "Data Source=(local);Initial Catalog=Db;Integrated Security=SSPI;";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
string sql = @"select top 1 * from tbl order by id desc";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
_info.Text = reader["title"].ToString();
}
reader.Close();
}
}
conn.Close();
}
又如:
string oSql=“select id,password,name,level,station,dept from verify”;//SQL語句
SqlCommand comm=new SqlCommand(oSql,con); //創建和聲明Command對象
con.Open();//在調用方法前打開數據庫連接,可以減少數據庫連接所花的時間,節省數據庫資源。
SqlDataReader dr=comm.ExecuteReader ();
While(dr.Read())
{
String id=“”;
id=dr[0].ToString();(0為第一列)或 id=dr[“id”].ToString();(引用字段名)或id= dr.GetString
(dr.GetOrdinal (“id"));
con.Close();//關閉數據庫連接
}