1. 程式人生 > >ADO.Net之SqlConnection、SqlCommand的應用

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語句