ADO.Net之SqlConnection、SqlCommand的应用

一、SqlConnection的应用

  要编写程序操作数据库,首先要连接到数据库。使用SqlConnection类可以连接到SQLServer数据库。

  操作如下:

  设计如下图所示Windows程序,单击“连接”按钮,连接AddressList

  

 

  (1)首先在代码中添加对System.Data.SqlClient命令空间的引用:

  using System.Data.SqlClient;

  (2)在“连接”按钮的单击事件中编写代码:  

  SqlConnection sqlConnection = new SqlConnection();
  sqlConnection.ConnectionString =
  "Server=(Local);Database=EduBaseDemo;Integrated Security=sspi";
  sqlConnection.Open();
  MessageBox.Show("打开数据库连接成功");
  sqlConnection.Close();
  MessageBox.Show("关闭数据库连接成功");

  运行程序:

  

  

  

 

   代码思维为:定义连接字符串(这里为Windows身份连接)→创建SqlConnection对象→打开数据库连接

二、SqlCommand的应用

  SqlCommand对象用于执行具体的SQL语句,如增加、删除、修改、查找。

  操作如下:

  设计如下图所示的用户登录界面,单击“登录”按钮,判断用户名、密码是否正确。

  

 

  “登录”按钮的单击事件代码如下: 

  SqlConnection sqlConnection = new SqlConnection();
  sqlConnection.ConnectionString =
  "Server=(local);Database=EduBaseDemo;Integrated Security=sspi";
  SqlCommand sqlCommand = new SqlCommand();
  sqlCommand.Connection = sqlConnection;
  sqlCommand.CommandText =
  "SELECT COUNT(1) FROM tb_User"
  + " WHERE No='" + this.txt_user.Text.Trim() + "'"
  + " AND Password=HASHBYTES('MD5','" + this.txt_pass.Text.Trim() + "');";
  sqlConnection.Open();
  int rowCount = (int)sqlCommand.ExecuteScalar();
  sqlConnection.Close();
  if (rowCount == 1)
  {
  MessageBox.Show("登录成功。");
  }
  else
  {
  MessageBox.Show("用户号/密码有误,请重新输入!");
  this.txt_pass.Focus();
  this.txt_pass.SelectAll();
  }

  “取消”按钮的单击事件代码:

  this.close();

  运行程序:

  

  

  代码思维:创建SqlConnection对象→定义SQL语句→SqlCommand对象→调用SqlCommand对象的某个方法,执行SQL语句

posted @ 2018-09-16 21:05  dearzy35  阅读(168)  评论(0编辑  收藏  举报