这就是我通常所做的:我创建一个类,例如 ConnectDB,并在该类中创建一个方法,例如 GetConnection。这是代码:
Imports System.Data
Imports System.Data.SqlClient
Public Class ConnectDB
Public Shared Function GetConnection() As SqlConnection
Dim dbConnString As String = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"
Return New SqlConnection(dbConnString)
End Function
End Class
Then from the method that needs a connection to the database, I call this function. Here is a sample code:
Imports System.Data.SqlClient
Public Class EmployeeDB
Public Shared Function GetEmployees() As List(Of Employee)
Dim con As SqlConnection = ConnectDB.GetConnection()
Dim selectStmt As String = "SELECT * FROM Employees"
Dim selectCmd As New SqlCommand(selectStmt, con)
Dim employees As New List(Of Employee)
Try
con.Open()
Dim reader As SqlDataReader = selectCmd.ExecuteReader()
Do While reader.Read
Dim employee as New Employee
employee.LastName = reader("LastName").ToString
employee.FirstName = reader("FirstName").ToString
...
employees.Add(employee)
Loop
reader.Close()
Catch ex As Exception
Throw ex
Finally
con.Close()
End Try
Return employees
End Function
End Class
您还可以修改selectStmt
字符串以包含过滤条件、参数和排序顺序,就像上面 Tim 的示例一样,并包含selectCmd.Parameters.AddWithValue("@<parameterName>", value)
每个参数。