1.基本连接步骤
使用SqlConnection、SqlCommand和SqlDataReader进行基础操作:
Imports System.Data.SqlClient
Public Sub ConnectToDatabase()
Dim connectionString As String = "Server=myServerAddress;Database=myDataBase;Integrated Security=True;"
Using connection As New SqlConnection(connectionString)
Try
connection.Open()
Dim query As String = "SELECT * FROM Users"
Using command As New SqlCommand(query, connection)
Using reader As SqlDataReader = command.ExecuteReader()
While reader.Read()
Console.WriteLine(reader("Username").ToString())
End While
End Using
End Using
Catch ex As SqlException
Console.WriteLine("SQL错误: " & ex.Message)
Catch ex As Exception
Console.WriteLine("常规错误: " & ex.Message)
End Try
End Using
End Sub
2.常见问题及解决方案
问题1:连接字符串错误
症状:SqlException提示"找不到服务器"或"登录失败"。
解决:
使用SqlConnectionStringBuilder避免格式错误:
Dim builder As New SqlConnectionStringBuilder()
builder.DataSource = "myServerAddress"
builder.InitialCatalog = "myDatabase"
builder.IntegratedSecurity = True ' Windows身份验证
' 或使用SQL身份验证:
' builder.UserID = "sa"
' builder.Password = "password"
Dim connectionString As String = builder.ConnectionString
确保服务器名称正确(本地实例可用.或(local))。
问题2:身份验证失败
解决:
Windows身份验证:确认应用程序运行账户有数据库权限。
SQL身份验证:检查用户名/密码,确保SQL Server启用"混合模式认证"。
问题3:网络/防火墙问题
解决:
使用telnet myServerAddress 1433测试端口连通性。
在SQL Server配置管理器中启用TCP/IP协议,并设置固定端口(如1433)。
问题4:权限不足
解决:
在SQL Server中为用户授予对应权限:
sql
USE myDatabase;
GRANT SELECT, INSERT ON Users TO [UserName];
3. 异常处理与资源管理
使用Using语句:自动释放连接、命令和读取器资源。
捕获特定异常:
Catch ex As SqlException When ex.Number = 18456 ' 登录失败
Console.WriteLine("用户名或密码错误。")
Catch ex As SqlException When ex.Number = -1 连接超时
Console.WriteLine("连接超时,请检查网络。")
4.数据处理注意事项
处理空值:
If Not reader.IsDBNull(reader.GetOrdinal("Email")) Then
Dim email As String = reader("Email").ToString()
End If
参数化查询(防SQL注入):
Dim query As String = "INSERT INTO Users (Username) VALUES (@Username)"
Using command As New SqlCommand(query, connection)
command.Parameters.AddWithValue("@Username", "JohnDoe")
command.ExecuteNonQuery()
End Using
5.事务与存储过程
事务示例:
Using transaction As SqlTransaction = connection.BeginTransaction()
Try
' 执行多个命令
transaction.Commit()
Catch
transaction.Rollback()
End Try
End Using
调用存储过程:
Using command As New SqlCommand("usp_GetUser", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("@UserId", 123)
End Using
6.配置文件管理
在App.config中存储连接字符串:
xml
<configuration>
<connectionStrings>
<add name="MyDB"
connectionString="Server=.;Database=MyDB;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
代码中读取:
Dim connectionString As String = ConfigurationManager.ConnectionStrings("MyDB").ConnectionString
7.性能优化
连接池:默认启用,避免手动开关连接。
异步操作:
Await connection.OpenAsync()
Await command.ExecuteNonQueryAsync()
设置超时:
command.CommandTimeout = 30 ' 秒
工具推荐
测试连接:使用SQL Server Management Studio (SSMS)。
检查协议:通过SQL Server配置管理器启用TCP/IP。
通过遵循以上步骤,可系统排查和解决VB.NET与SQL Server连接问题。遇到复杂情况时,查看具体错误代码并参考官方文档获取进一步支持。