1. 程式人生 > 實用技巧 >C#| 建立資料庫連線 | SQL server

C#| 建立資料庫連線 | SQL server

使用SqlConnection連線到SQL Server2019

且返回表的行數。

1、介面設計

2、程式碼設計

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 using System.Data.SqlClient; 11 12 namespace Chapter13 13 { 14 public partial class Form1 : Form 15 { 16 public Form1() 17 { 18 InitializeComponent(); 19 } 20 21 private void Form1_Load(object sender, EventArgs e) 22 { 23 //SqlConnection conn = new SqlConnection(@"server=.\SQLEXPRESS;integrated security=true;database=MyBookInfo");
24 25 //SqlCommand cmd = new SqlCommand(); 26 27 //try 28 //{ 29 // conn.Open(); 30 31 // txtComandText.AppendText("Connection opened \n"); 32 // txtComandText.AppendText("Command created.\n"); 33 34 // cmd.CommandText = @"select * from BookInfo ";
35 36 // txtComandText.AppendText("Ready to execute SQL Statement:\n\t\t\t" + cmd.CommandText); 37 //} 38 //catch(SqlException ex) 39 //{ 40 // MessageBox.Show(ex.Message + ex.StackTrace, "Exception Details"); 41 //} 42 //finally 43 //{ 44 // conn.Close(); 45 // txtComandText.AppendText("\nConnection Closed."); 46 //} 47 48 } 49 50 private void btnRowCount_Click(object sender, EventArgs e) 51 { 52 SqlConnection conn = new SqlConnection(@"server=.\SQLEXPRESS;integrated security=true;database=MyBookInfo"); 53 54 //建立連線字串,conn
55 56 string sql = @"select count(*) from BookInfo"; 57 58 //sql連線語句 59 60 SqlCommand cmd = new SqlCommand(sql, conn); 61 62 //執行連線命令 63 64 txtScalar.AppendText("Command created and connected.\n"); 65 66 try 67 { 68 conn.Open(); 69 txtScalar.AppendText("Number of Books is :"); 70 71 txtScalar.AppendText(cmd.ExecuteScalar().ToString()); 72 txtScalar.AppendText("\n"); 73 74 } 75 catch(SqlException ex) 76 { 77 MessageBox.Show(ex.ToString()); 78 } 79 finally 80 { 81 conn.Close(); 82 txtScalar.AppendText("\nConnection Closed."); 83 } 84 } 85 } 86 }

3、詳細說明

1、設計好介面以後,點選‘Count Rows’ 生成第21行程式碼。

2、在21行程式碼內填寫連線所需程式碼。

3、程式碼剖析:

該語句中@“server=.\”中的 .(點) 表示本地伺服器。而 \ (斜線) 後面表示執行在資料庫伺服器上的例項名稱。

.\SQLEXPRESS 也可以寫成 localhost\SQLEXPRESS 或者 (local)\SQLEXPRESS

intergrated security=true 則指定要通過Windows 身份驗證來登入。

database=MyBookInfo 則是制定資料庫名稱的語句。這裡的資料庫的名稱是MyBookInfo

常用的可以新增在連線字串裡的引數:

名稱 別名 預設值 允許值 說明
Data Source

server 、Address、Addr、

Network、Address

None 伺服器名或網路地址 目標SQL Server 例項的名稱
Initial Catalog Database None 伺服器上的任何資料庫 資料庫名
Connect Timeout Connection Timeout 15

0~32767

連線的等待時間(秒)
Integrated Security Trusted_Connection false Ture 、false、Yes、no 、sspi 指定身份驗證模式

建立SQL語句。語句功能:數表格的行數。

可以根據需要建立不同功能的語句。

txtScalar 是文字輸入框的名字。

try catch 語句。

cmd.ExecuteScalar() 可以理解為在SQL中執行你寫好的 SQL語句,然後把結果返回。

AppendText 則是把返回的資料顯示出來。