c#資料庫連接學習

來源:互聯網
上載者:User

標籤: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#資料庫連接學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.