本课学习目标
- 在 Visual Studio 打开 SQL Server Object Explorer。
- 连接 (localdb)\MSSQLLocalDB。
- 创建 StudentManagementDB 数据库。
- 通过 T-SQL 创建 Students 表。
- 安装并使用 Microsoft.Data.SqlClient。
- 建立 DatabaseHelper.vb 与连接字符串。
- 使用 SqlConnection.Open() 测试连接。
- 使用 ExecuteScalar() 读取学生人数。
24.1 为什么选择 LocalDB?
LocalDB 是 SQL Server Express 的轻量本机开发方式。它适合学习真正的 SQL Server 表、主键、查询和连接,同时可以直接在 Visual Studio 内管理。
适合学习
数据库运行在当前 Windows 用户环境中,适合桌面应用开发与测试。
使用 T-SQL
可以真正执行 CREATE TABLE、SELECT、INSERT、UPDATE 和 DELETE。
IDE 内管理
SQL Server Object Explorer 可以查看数据库、表、数据和执行查询。
24.2 打开 SQL Server Object Explorer
在 Visual Studio 菜单选择:
View
→ SQL Server Object Explorer
找到:
SQL Server
└─ (localdb)\MSSQLLocalDB
24.3 创建 StudentManagementDB
找到 Databases 节点。
选择 Add New Database。
StudentManagementDB。
确认数据库已经出现。
24.4 打开 New Query
右键 StudentManagementDB → New Query。确认查询窗口连接的数据库是 StudentManagementDB,而不是 master。
24.5 创建 Students 表
CREATE TABLE dbo.Students
(
StudentID INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(100) NOT NULL,
Course NVARCHAR(100) NOT NULL,
Score DECIMAL(5,2) NOT NULL
CHECK (Score BETWEEN 0 AND 100)
);
执行后刷新 Tables,应看到:
dbo.Students
24.6 理解表结构
| 字段 | SQL 类型 | 设置 | 意义 |
|---|---|---|---|
| StudentID | INT | IDENTITY + PRIMARY KEY | 自动编号并唯一识别学生。 |
| Name | NVARCHAR(100) | NOT NULL | 学生姓名。 |
| Course | NVARCHAR(100) | NOT NULL | 课程名称。 |
| Score | DECIMAL(5,2) | CHECK 0–100 | 学生成绩。 |
24.7 加入测试资料
INSERT INTO dbo.Students
(Name, Course, Score)
VALUES
(N'李明', N'Visual Basic 2026', 88),
(N'王芳', N'C# Programming', 76),
(N'陈伟', N'Python Programming', 91);
然后执行:
SELECT StudentID, Name, Course, Score
FROM dbo.Students
ORDER BY StudentID;
如果看到三笔记录,数据库和表已经建立成功。
24.8 创建 Windows Forms 项目
建立:
StudentDatabaseConnection2026
使用 Visual Basic、Windows Forms 和 .NET 10。
24.9 安装 Microsoft.Data.SqlClient
选择 Manage NuGet Packages。
搜索 Microsoft.Data.SqlClient。
选择适用于当前项目的稳定版本。
安装后可以使用:
Imports Microsoft.Data.SqlClient
24.10 建立 DatabaseHelper.vb
Public NotInheritable Class DatabaseHelper
Private Sub New()
End Sub
Public Shared ReadOnly Property ConnectionString As String
Get
Return
"Server=(localdb)\MSSQLLocalDB;" &
"Database=StudentManagementDB;" &
"Integrated Security=True;" &
"TrustServerCertificate=True;"
End Get
End Property
End Class
Server=(localdb)\MSSQLLocalDB
Database=StudentManagementDB
Integrated Security=True
24.11 理解连接字符串
| 设置 | 作用 |
|---|---|
| Server=(localdb)\MSSQLLocalDB | 指定 LocalDB 实例。 |
| Database=StudentManagementDB | 指定目标数据库。 |
| Integrated Security=True | 使用当前 Windows 身份。 |
| TrustServerCertificate=True | 简化本机教学环境的证书配置。 |
24.12 设计测试界面
Database: StudentManagementDB
State: Open
Students 表目前有 3 笔记录。
加入:
| 控件 | Name | 用途 |
|---|---|---|
| Button | btnTestConnection | 测试连接 |
| Button | btnCountStudents | 读取学生人数 |
| Label | lblStatus | 显示连接状态 |
| TextBox | txtInfo | Multiline = True;ReadOnly = True |
24.13 测试 SqlConnection
Form1.vb 顶部:
Imports Microsoft.Data.SqlClient
按钮代码:
Private Sub btnTestConnection_Click(
sender As Object,
e As EventArgs) Handles btnTestConnection.Click
Try
Using connection As New SqlConnection(
DatabaseHelper.ConnectionString)
connection.Open()
lblStatus.Text =
"数据库连接成功。"
txtInfo.Text =
$"Server: {connection.DataSource}" &
Environment.NewLine &
$"Database: {connection.Database}" &
Environment.NewLine &
$"State: {connection.State}"
End Using
Catch ex As SqlException
lblStatus.Text =
"数据库连接失败。"
MessageBox.Show(
ex.Message,
"SQL Server 错误",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
Catch ex As Exception
MessageBox.Show(
ex.Message,
"错误",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End Sub
24.14 为什么要使用 Using?
Using connection As New SqlConnection(
DatabaseHelper.ConnectionString)
connection.Open()
' 执行数据库操作
End Using
离开 Using 后,连接对象会自动释放。数据库连接建议遵循“需要时才打开,用完尽快释放”的原则。
24.15 执行第一个查询:COUNT(*)
Private Sub btnCountStudents_Click(
sender As Object,
e As EventArgs) Handles btnCountStudents.Click
Const sql As String =
"SELECT COUNT(*) FROM dbo.Students;"
Try
Using connection As New SqlConnection(
DatabaseHelper.ConnectionString)
Using command As New SqlCommand(
sql,
connection)
connection.Open()
Dim studentCount As Integer =
Convert.ToInt32(
command.ExecuteScalar())
lblStatus.Text =
"查询成功。"
txtInfo.Text =
$"Students 表目前有 {studentCount} 笔记录。"
End Using
End Using
Catch ex As SqlException
MessageBox.Show(
ex.Message,
"数据库错误",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End Sub
ExecuteScalar() 适合只返回一个值的查询,例如 COUNT、MAX、MIN 或 AVG。
24.16 完整连接流程
24.17 连接失败时怎样检查?
SQL Server Object Explorer 是否能展开 (localdb)\MSSQLLocalDB?
是否确实叫 StudentManagementDB?
Tables 下是否看得到 dbo.Students?
Microsoft.Data.SqlClient 是否已安装?
ex.Message 往往能指出服务器、数据库或权限问题。
24.18 初学者常见错误
New Query 连到 master
建表前确认目标数据库是 StudentManagementDB。
数据库名称不一致
Object Explorer 中的名称必须与连接字符串一致。
忘记安装 SqlClient
没有正确引用包时,Imports Microsoft.Data.SqlClient 和 SqlConnection 会报错。
长期保持全局 Open 连接
建议每个数据库操作使用 Using,完成后立即释放。
24.19 小练习
- 把 COUNT 查询改成 SELECT MAX(Score) FROM dbo.Students。
- 再加入一位学生,并确认 Count 增加。
- 执行 SELECT * FROM dbo.Students ORDER BY Score DESC。
- 故意把连接字符串中的数据库名改错,观察 SqlException;然后恢复正确名称。
- 在 SQL Server Object Explorer 查看 dbo.Students 的 Columns、Keys 与 Constraints。
本课复习
- LocalDB 为什么适合本机开发学习?
- 怎样在 Visual Studio 打开 SQL Server Object Explorer?
- StudentID 为什么使用 PRIMARY KEY 与 IDENTITY?
- Microsoft.Data.SqlClient 在项目中负责什么?
- 连接字符串的 Server 与 Database 分别代表什么?
- SqlConnection.Open() 做什么?
- 为什么 SqlConnection 适合放在 Using 区块?
- ExecuteScalar() 适合哪一种查询?