代码改变世界

DataReader 标准写法

2020-06-09 20:06  idea555  阅读(113)  评论(0)    收藏  举报
  1. //“查询”按钮单击事件
  2. private void button1_Click(object sender, EventArgs e)
  3. {
  4. //编写数据库连接串
  5. string connStr = "Data Source=.;Initial Catalog=test;User ID=sa;Password=root";
  6. //创建 SqlConnection的实例
  7. SqlConnection conn = null;
  8. //定义SqlDataReader类的对象
  9. SqlDataReader dr = null;
  10. try
  11. {
  12. conn = new SqlConnection(connStr);
  13. //打开数据库连接
  14. conn.Open();
  15. string sql = "select id,password from userinfo where name='{0}'";
  16. //填充SQL语句
  17. sql = string.Format(sql, textBox1.Text);
  18. //创建SqlCommand对象
  19. SqlCommand cmd = new SqlCommand(sql, conn);
  20. //执行Sql语句
  21. dr = cmd.ExecuteReader();
  22. //判断SQL语句是否执行成功
  23. if (dr.Read())
  24. {
  25. //读取指定用户名对应的用户编号和密码
  26. string msg = "用户编号:" + dr[0] + " 密码:" + dr[1];
  27. //将msg的值显示在标签上
  28. label2.Text = msg;
  29. }
  30. }
  31. catch (Exception ex)
  32. {
  33. MessageBox.Show("查询失败!" + ex.Message);
  34. }
  35. finally
  36. {
  37. if (dr != null)
  38. {
  39. //判断dr不为空,关闭SqlDataReader对象
  40. dr.Close();
  41. }
  42. if (conn != null)
  43. {
  44. //关闭数据库连接
  45. conn.Close();
  46. }
  47. }
  48. }