C#中使用DbHelper连接SqlServer数据库
生活随笔
收集整理的這篇文章主要介紹了
C#中使用DbHelper连接SqlServer数据库
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
場(chǎng)景
C#的窗體應(yīng)用中,經(jīng)常要連接數(shù)據(jù)庫(kù)進(jìn)行相應(yīng)的操作。
進(jìn)行簡(jiǎn)單的數(shù)據(jù)庫(kù)連接測(cè)試。
實(shí)現(xiàn)
新建窗體應(yīng)用,在工具箱中拖拽一個(gè)Button按鈕。
?
右擊項(xiàng)目名-添加-類
DBHelper類,連接數(shù)據(jù)庫(kù)工具類。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient;namespace DBDemo {public class DBHelper{private static string connString = "data source=.;initial catalog= 數(shù)據(jù)庫(kù)名;userid=sa;pwd=123";//獲得數(shù)據(jù)庫(kù)聯(lián)接public static SqlConnection GetConnection(){SqlConnection connection = new SqlConnection(connString);return connection;}//關(guān)閉數(shù)據(jù)庫(kù)聯(lián)接public static void CloseConnection(SqlConnection connection){connection.Close();}} }回到窗體中雙擊按鈕,進(jìn)入button按鈕的點(diǎn)擊事件中
private void btnTest_Click(object sender, EventArgs e){SqlConnection connection = DBHelper.GetConnection();try{connection.Open();MessageBox.Show("打開數(shù)據(jù)庫(kù)連接成功!");}catch(Exception ex){MessageBox.Show("打開數(shù)據(jù)庫(kù)失敗!"+ex.Message);}}?
運(yùn)行程序,點(diǎn)擊按鈕。
?
如果連接String不對(duì)
?
源碼下載
https://download.csdn.net/download/badao_liumang_qizhi/11561530
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的C#中使用DbHelper连接SqlServer数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CS中实现简单的注册验证窗体程序
- 下一篇: C#中ArrayList的简单使用