ADO.NET连接数据库
就寫(xiě)一個(gè)簡(jiǎn)單連接數(shù)據(jù)庫(kù)示例
新建一個(gè)Winfrom窗體
在添加一個(gè)button控件
下面的代碼我全部注釋了
連接數(shù)據(jù)庫(kù)示例如下代碼
?
?private void button1_Click(object sender, EventArgs e)
??????? {
??????????? try
??????????? {
??????????????? //server,代表服務(wù)器地址;intergrated security,標(biāo)識(shí)認(rèn)證方式,此處采用的windows集成驗(yàn)證方式;
??????????????? //database代表要訪問(wèn)的數(shù)據(jù)庫(kù)
??????????????? //使用windows集成驗(yàn)證方式
??????????????? // string strDB = "server=(local);integrated security=SSPI;database=Stu";
??????????????? //使用數(shù)據(jù)庫(kù)用戶(hù)名密碼訪問(wèn)
??????????????? string strDB = "server=(local);database=Stu;uid=sa;pwd=mima";
??????????????? //聲明概要執(zhí)行的數(shù)據(jù)庫(kù)命令
??????????????? string strcmd = "SELECT COUNT(*) FROM student";
??????????????? //創(chuàng)建Connection對(duì)象
??????????????? SqlConnection connection = new SqlConnection(strDB);
??????????????? //創(chuàng)建Command對(duì)象
??????????????? SqlCommand sqlCmd = new SqlCommand(strcmd,connection);
??????????????? //打開(kāi)數(shù)據(jù)庫(kù)
??????????????? connection.Open();
??????????????? //調(diào)用ExecuteScalar方法,返回查詢(xún)的值,注意,此方法返回是表中的第一行第一列
??????????????? int count = (int)sqlCmd.ExecuteScalar();
?????????????? // MessageBox.Show("打開(kāi)數(shù)據(jù)庫(kù)連接");
??????????????? //關(guān)閉數(shù)據(jù)庫(kù)
??????????????? connection.Close();
?????????????? // MessageBox.Show("關(guān)閉數(shù)據(jù)庫(kù)連接");
??????????????? MessageBox.Show("學(xué)生人數(shù)為:"+ count.ToString() +"人!");
??????????? }
??????????? catch (SqlException ex)
??????????? {
??????????????? MessageBox.Show(ex.Message);
??????????????
??????????? }
??????????? finally
??????????? {
?
??????????? }
?????
??????? }
?
轉(zhuǎn)載于:https://www.cnblogs.com/LeeYongze/archive/2009/11/05/1596897.html
總結(jié)
以上是生活随笔為你收集整理的ADO.NET连接数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 63. Unique Paths II
- 下一篇: [翻译]你或许还未听说过的一些ASP.N