我在对问题的评论中开始了这一点,但让我向您展示一个大大改进的数据访问类的开始:
Public Class SqlDataHelper
Private Property ConnectionString() As String
Get
'return the connection string, perhaps read/cached from a config file
'I'll often require this as an argument to the class constructor as well
End Get
'May not need a setter, depending on how you build this
End Property
Private Function GetConnection() As SqlConnection
GetConnection = New SqlConnection(ConnectionString)
GetConnection.Open()
End Function
Private Function GetDataTable(ByVal query As String, ByVal ParamArray args() As SqlParameter) As DataTable
Dim ds As New DataTable
Dim cmd As New SqlCommand(query, GetConnection())
If args IsNot Nothing Then
For Each p As SqlParameter In args
cmd.Parameters.Add(p)
Next p
End If
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
Return dt
End Function
Private Function UpdateData(ByVal command As String, ByVal ParamArray args() As SqlParameter) As Integer
Using cn As SqlConnection = GetConnection(), _
cmd As New SqlCommand(command, cn)
If args IsNot Nothing Then
For Each p As SqlParameter In args
cmd.Parameters.Add(p)
Next p
End If
Return cmd.ExecuteNonQuery()
End Function
Private Function GetSingleValue(ByVal query As String, ByVal ParamArray args() As SqlParameter) As Object
Using cn As SqlConnection = GetConnection(), _
cmd As New SqlCommand(query, cn)
If args IsNot Nothing Then
For Each p As SqlParameter In args
cmd.Parameters.Add(p)
Next p
End If
Return cmd.ExecuteScalar()
End Function
Public Function ReadFunctionID() As DataTable
Return GetDataTable("SELECT fld_functionid FROM tbl_users_function_permission", Nothing)
End Function
Public Function ReadFunctionIDByUser(ByVal UserID As Integer) As DataTable
Return GetDataTable("SELECT fld_functionid FROM tbl_users_function_permission WHERE UserID = @UserID", _
New SqlParameter("@UserID", UserID))
End Function
End Class
让我们仔细看看这段代码中的一些改进。首先,请注意什么是公共与什么是私有。在任何时候,您都不想接受来自表示层的临时 sql 字符串。这并不意味着您不能使用 ad hoc sql,只是您希望将数据和演示部分分开。
看看类中最后两个函数是如何处理参数数据的。Nothing
在不使用任何参数时需要使用显式的事实是此代码的一个特性。它不断提醒您应该使用查询参数。如果您不知道什么是 sql 注入以及如何防止它,那么您不应该编写数据库代码!
希望这对您有所帮助。