1.基本連接步驟
使用SqlConnection、SqlCommand和SqlDataReader進行基礎操作:
vb.net
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避免格式錯誤:
vb.net
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語句:自動釋放連接、命令和讀取器資源。
捕獲特定異常:
vb.net
Catch ex As SqlException When ex.Number = 18456 ?' 登錄失敗
? ? Console.WriteLine("用戶名或密碼錯誤。")
Catch ex As SqlException When ex.Number = -1 連接超時
? ? Console.WriteLine("連接超時,請檢查網絡。")
4.數據處理注意事項
處理空值:
vb.net
If Not reader.IsDBNull(reader.GetOrdinal("Email")) Then
? ? Dim email As String = reader("Email").ToString()
End If
參數化查詢(防SQL注入):
vb.net
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.事務與存儲過程
事務示例:
vb.net
Using transaction As SqlTransaction = connection.BeginTransaction()
? ? Try
? ? ? ? ' 執行多個命令
? ? ? ? transaction.Commit()
? ? Catch
? ? ? ? transaction.Rollback()
? ? End Try
End Using
調用存儲過程:
vb.net
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>
代碼中讀取:
vb.net
Dim connectionString As String = ConfigurationManager.ConnectionStrings("MyDB").ConnectionString
7.性能優化
連接池:默認啟用,避免手動開關連接。
異步操作:
vb.net
Await connection.OpenAsync()
Await command.ExecuteNonQueryAsync()
設置超時:
vb.net
command.CommandTimeout = 30 ?' 秒
工具推薦
測試連接:使用SQL Server Management Studio (SSMS)。
檢查協議:通過SQL Server配置管理器啟用TCP/IP。
通過遵循以上步驟,可系統排查和解決VB.NET與SQL Server連接問題。遇到復雜情況時,查看具體錯誤代碼并參考官方文檔獲取進一步支持。