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