关于使用VB.NET连接SQL数据库的语句和注意事项,综合整理如下:
一、基础连接步骤
添加数据库引用
需在项目中添加对`System.Data.SqlClient`的引用,通常通过“引用”菜单或NuGet包管理器完成。
创建连接字符串
连接字符串包含数据库服务器地址、数据库名称、认证信息等,格式如下:
```vb
Dim connStr As String = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
```
- `Server`:数据库服务器地址(如`192.168.1.79`或`localhost`)
- `Database`:目标数据库名称(如`Charge_sys`)
- `User Id`:数据库用户名(如`sa`)
- `Password`:对应用户名的密码
建立数据库连接
使用`SqlConnection`类创建连接对象,并通过`Open`方法建立连接:
```vb
Using connection As New SqlConnection(connStr)
connection.Open()
' 执行数据库操作
End Using
```
> 注意:建议使用`Using`语句确保连接被正确关闭
二、常见注意事项
连接字符串安全
- 不要在代码中硬编码密码,建议使用配置文件或环境变量存储敏感信息
- 对于集成安全性(如Windows身份验证),可设置`Integrated Security=True`
异常处理
使用`Try...Catch`块捕获数据库操作中的异常,避免程序崩溃:
```vb
Try
connection.Open()
' 执行SQL命令
Catch ex As SqlException
Console.WriteLine("数据库错误: " & ex.Message)
Catch ex As Exception
Console.WriteLine("其他错误: " & ex.Message)
Finally
If connection.State = ConnectionState.Open Then
connection.Close()
End If
End Try
```
资源管理
- 使用`Using`语句自动管理数据库连接和命令对象的生命周期
- 避免长时间占用连接,操作完成后及时关闭
三、扩展应用
执行SQL命令
使用`SqlCommand`对象执行`SELECT`、`INSERT`、`UPDATE`等操作:
```vb
Dim sql As String = "SELECT name FROM sys.objects WHERE type = 'U' ORDER BY name"
Using command As New SqlCommand(sql, connection)
Using reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine(reader.GetString(0))
End While
End Using
End Using
```
参数化查询
为防止SQL注入,建议使用参数化查询:
```vb
Dim sql As String = "INSERT INTO users (name, age) VALUES (@name, @age)"
Using command As New SqlCommand(sql, connection)
command.Parameters.AddWithValue("@name", "张三")
command.Parameters.AddWithValue("@age", 30)
command.ExecuteNonQuery()
End Using
```
四、工具辅助
SQL Server Management Studio (SSMS)
可通过SSMS可视化管理数据库,测试连接字符串和SQL语句
以上内容综合了基础语法与实际应用要点,建议结合具体项目需求进一步学习。