1 /*通過C#winform程序訪問數據庫數據 2 3 用到的命名空間和變量類型: 4 5 using System.Data.SqlClient; 6 7 SqlConnection;數據庫連接類 8 9 SqlCommand;數據庫操作類 10 11 SqlDataReader:讀取 */ 12 13 //登錄按鈕代碼 14 private void button1_Click(object sender, EventArgs e) 15 { 16 if (textBox1.Text == "") 17 MessageBox.Show("用戶名不能為空!", "提示"); 18 else if (textBox2.Text == "") 19 MessageBox.Show("密碼不能為空!", "提示"); 20 try //try...catch...異常處理語句 21 { 22 string name, pass; 23 bool flag = false; 24 name = textBox1.Text; 25 pass = textBox2.Text; //獲取用戶名,密碼 26 string str = "Data Source=SQL服務器名稱;Initial Catalog=數據庫名;User ID=登錄名;Password=密碼;"; 27 SqlConnection myConn = new SqlConnection(str);//創建數據庫連接類的對象 28 myConn.Open(); //將連接打開 29 //SQL語句:從數據庫的登錄表中搜索登錄名,密碼 30 string sqlstring = "select username,password from users where username='" +name + "'and password='" + pass + "'"; 31 //執行con對象的函數,返回一個SqlCommand類型的對象 32 SqlCommand command = new SqlCommand(sqlstring, myConn); 33 //用cmd的函數執行語句,返回SqlDataReader對象thisReader,thisReader就是返回的結果集(也就是數據庫中查詢到的表數據) 34 SqlDataReader thisReader = command.ExecuteReader(); 35 //判斷用戶名及密碼是否正確,對flag進行賦值 36 while (thisReader.Read()) 37 { 38 if ((thisReader.GetValue(0).ToString().Trim()) == (name.ToString().Trim())) 39 { 40 if (thisReader.GetValue(1).ToString().Trim() == pass.ToString().Trim()) 41 { 42 flag = true; 43 } 44 } 45 } 46 //用完后關閉連接,以免影響其他程序訪問 47 myConn.Close(); 48 if (flag) 49 { 50 MessageBox.Show("登陸成功!"); 51 Form2 F = new Form2(); //顯示主頁面 52 F.Show(); 53 this.Hide(); 54 } 55 else 56 { 57 MessageBox.Show("請檢查你的用戶名和密碼!"); 58 textBox1.Focus(); 59 } 60 } 61 catch (Exception ex2) 62 { 63 MessageBox.Show("連接遠程SQL數據庫發生錯誤:" + ex2.ToString(), "錯誤!"); 64 }