標籤:show nbsp exce info mes while 擷取 winform end
/*通過C#winform程式訪問資料庫資料
用到的命名空間和變數類型:
using System.Data.SqlClient;
SqlConnection;資料庫連接類
SqlCommand;資料庫操作類
SqlDataReader:讀取 */
//登入按鈕代碼
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
MessageBox.Show("使用者名稱不可為空!", "提示");
else if (textBox2.Text == "")
MessageBox.Show("密碼不可為空!", "提示");
try //try...catch...異常處理語句
{
string name, pass;
bool flag = false;
name = textBox1.Text;
pass = textBox2.Text; //擷取使用者名稱,密碼
string str = "Data Source=SQL伺服器名稱;Initial Catalog=資料庫名;User ID=登入名稱;Password=密碼;";
SqlConnection myConn = new SqlConnection(str);//建立資料庫連接類的對象
myConn.Open(); //將串連開啟
//SQL語句:從資料庫的登入表中搜尋登入名稱,密碼
string sqlstring = "select username,password from users where username=‘" +name + "‘and password=‘" + pass + "‘";
//執行con對象的函數,返回一個SqlCommand類型的對象
SqlCommand command = new SqlCommand(sqlstring, myConn);
//用cmd的函數執行語句,返回SqlDataReader對象thisReader,thisReader就是返回的結果集(也就是資料庫中查詢到的表資料)
SqlDataReader thisReader = command.ExecuteReader();
//判斷使用者名稱及密碼是否正確,對flag進行賦值
while (thisReader.Read())
{
if ((thisReader.GetValue(0).ToString().Trim()) == (name.ToString().Trim()))
{
if (thisReader.GetValue(1).ToString().Trim() == pass.ToString().Trim())
{
flag = true;
}
}
}
//用完後關閉串連,以免影響其他程式訪問
myConn.Close();
if (flag)
{
MessageBox.Show("登陸成功!");
Form2 F = new Form2(); //顯示首頁面
F.Show();
this.Hide();
}
else
{
MessageBox.Show("請檢查你的使用者名稱和密碼!");
textBox1.Focus();
}
}
catch (Exception ex2)
{
MessageBox.Show("串連遠程SQL資料庫發生錯誤:" + ex2.ToString(), "錯誤!");
}
轉寄自:http://www.cnblogs.com/q1092813103/p/5655881.html
c#資料庫連接學習