且返回表的行數。
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 則是把返回的數據顯示出來。
參考書籍:《C# 2012 數據庫編程入門經典》(第五版)【美】Vidya Vrat Agarwal 清華大學出版社