SqlDataReader对象每次从查询结果中读取一行到内存中,对于sql数据库,如果只需要顺序读取,可以优先选择SqlDataReader,其对数据库的读取速度非常快。
调用SqlDataReader对象的ExecuteReader方法创建SqlDataReader对象;
conn.Open();
SqlDataReader dr= cmd.ExecuteReader();
例:
private void btn_login_Click(object sender, EventArgs e)
{
if (txb_user.Text.Trim() == "" || txb_pwd.Text.Trim() == "")
{
MessageBox.Show("用户名或密码不能为空");
txb_user.Focus();
return;
}
string connString = @"Data Source=WIN-14UH8IJFB82; Initial Catalog=YaoDian;uid=sa;pwd=2789555456";
SqlConnection connection = new SqlConnection(connString);
string sqlStr = string.Format("select count(*)from[tb_login] where User='{0}' and password='{1}'",
txb_user.Text.Trim(), txb_pwd.Text.Trim());
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sqlStr, conn);
conn.Open();
SqlDataReader sdr = cmd .ExecuteReader ();
if (sdr .Read())
{
MessageBox.Show("登录成功。");
}
else
{
MessageBox.Show("用户号/密码有误,请重新输入!");
this.txb_pwd.Focus();
this.txb_pwd.SelectAll();
}
sdr.Close();
}
}