这几天在Sql命令中嵌入变量,用SqlParameter数组传值,代码如下:
''' <summary>
''' 增加卡信息函数
''' </summary>
''' <param name="card">实体类</param>
''' <returns>返回Boolean类型,是否添加成功</returns>
''' <remarks></remarks>
Public Function AddCard(card As CardEntity) As Boolean Implements ICard.AddCard
Dim strSQL As String 'Sql字符串
Dim i As Integer '受影响的行数
Dim Addresult As Boolean
'参数集合
Dim param As SqlParameter()
param = New SqlParameter() {
New SqlParameter("@strstudentID", card.studentID),
New SqlParameter("@strcardNo", card.cardNo),
New SqlParameter("@strcardCash", card.cardCash),
New SqlParameter("@strhandlers", card.handlers),
New SqlParameter("@strstate", card.state),
New SqlParameter("@strisCheck", card.isCheck),
New SqlParameter("@strcardDate", card.cardDate),
New SqlParameter("@strcardTime", card.cardTime)
}
'增加数据语句
strSQL = "insert into T_Card(studentID,cardNo,cardCash,handlers,state,isCheck,cardDate,cardTime)" & "values(@strstudentID,@strcardNo,@strcardCash,@strhandlers,@strstate,@strisCheck,@strcardDate,@strcardTime)"
'用Sqlhelper类
i = SqlHelper.DBSqlhelper.ExccuteNoQuery(strSQL, CommandType.Text, param)
If i > 0 Then
Addresult = True
End If
Return Addresult
End Function
运行了半天死活不行,仔细看一下提示:位置0处没有任何行
调试了一下,发现SQL语句写的参数不对应,修改好了,又出现问题了。
提示:参数化查询,未提供该参数
经查询是没有给参数赋值。从这也证明了Sqlparameter的参数集合中的参数必须要都写上才能执行。证明了Sqlparameter的防注入,很好用,只要一个参数集合就可以把所有参数传递进去。
在U层给实体赋值:
'卡实体赋值
Dim card As New Entity.CardEntity
card.cardNo = txtCardno.Text
card.cardCash = txtCash.Text
card.state = txtState.Text
card.studentID = txtStudentID.Text
card.handlers = "Liu"
card.isCheck = "未结账"
card.cardDate = Now
card.cardTime = Now