且返回表的行数。
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 清华大学出版社