我是新上课的,我想创建一个SqlCommandManager
课程,但我无法弄清楚如何在课堂上传递SqlParameter
。
例如,如果我想插入数据,我会像下面的客户端一样使用我的类。
'Client
Dim m_SqlComManager as new SQLCommandManager("MyConnectionString")
m_SqlCommandManager.Commandtext = "INSERT INTO [TableName]([Field1],[Field2])VALUES(@Field1,Field2);"
m_SqlCommandManager.Parameters.AddWithValue("@Field1","SomeValue1")
m_SqlCommandManager.Parameters.AddWithValue("@Field2","SomeValue2")
m_SqlCommandManager.ExecuteNonQuery()
'Here is my class
Imports System.Data.SqlClient
Public Class SQLCommandManager
Private m_SqlParameters As SqlParameter()
Private m_Commandtext As String
Private m_ConStr As String
Public WriteOnly Property SQlParameter() As SqlParameter()
Set(ByVal value As SqlParameter())
value = m_SqlParameters
End Set
End Property
Public Property CommandText() As String
Get
Return m_Commandtext
End Get
Set(ByVal value As String)
value = m_Commandtext
End Set
End Property
Public Sub New(ByVal con As String)
m_ConStr = con
End Sub
Public Sub ExecuteNonQuery()
Using con As New SqlConnection(m_ConStr)
Using com As New SqlCommand
com.Connection = con
com.CommandText = m_Commandtext
'Please help
'How can i insert parameter here from client..
If con.State = ConnectionState.Closed Then
con.Open()
End If
com.ExecuteNonQuery()
End Using
End Using
End Sub
End Class
如何在ExecuteNonQuery
方法之前设置参数?
提前致谢..
答案 0 :(得分:1)
我会做这样的事情:
Public Class SqlCommandManager
Private m_SqlParameters As List(Of SqlParameter)
Private m_Commandtext As String
Private m_ConStr As String
Public Sub New()
m_SqlParameters = New List(Of SqlParameter)()
End Sub
Public ReadOnly Property SqlParameters() As List(Of SqlParameter)
Get
Return m_SqlParameters
End Get
End Property
Public Property CommandText() As String
Get
Return m_Commandtext
End Get
Set
value = m_Commandtext
End Set
End Property
Public Sub New(con As String)
m_ConStr = con
End Sub
Public Sub ExecuteNonQuery()
Using con As New SqlConnection(m_ConStr)
Using com As New SqlCommand(m_Commandtext, con)
com.Parameters.AddRange(m_SqlParameters.ToArray())
con.Open()
com.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
End Class
我改变了什么:
将班级名称更改为SqlCommandManager
以符合Microsoft的建议(不要在缩写中大写超过2个字母; IO
没问题,Sql
和Xml
不应全部大写)
我会使用List(Of SqlParameter)
而不是数组 - 更容易处理,更容易添加其他参数
我更喜欢将CommandText
和SqlConnection
权限传递给SqlCommand
的构造函数 - 这样,你绝对不会忘记这两个重要的信息! / p>
在.ExecuteQuery
之前,只需拨打SqlCommand