如何使用vb.net使用executescaler从数据库填充值
我在ms access中有一个表名为regn的数据库。我想使用命令文本和executescaler填充字段名nocount。这是我的密码:如何使用vb.net使用executescaler从数据库填充值,vb.net,Vb.net,我在ms access中有一个表名为regn的数据库。我想使用命令文本和executescaler填充字段名nocount。这是我的密码: Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click dim i as integer If cn.State = ConnectionState.Open Then cn.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
dim i as integer
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
cmd.CommandText = "select nocount from regn where pname='" & PNAMETextBox.Text & "' And fname='" & FNAMETextBox.Text & "' And dob='" & DOBDateTimePicker.Text & "' "
i = cmd.ExecuteScalar
cn.Close()
如果显示变量i,则可以看到满足给定条件的nocount中的第一个值。这假设您的连接是在其他地方建立的,这与上面代码片段中的情况类似。如果您只是想获得nocount,则需要将该命令设置为连接。下面是一个参数化的示例,它将保护您的SQL注入漏洞:
' Assuming you're initializing the connection elsewhere, this will create the command AND set it's
' connection to your connection
Using cmd As SqlCommand = cn.CreateCommand
' Parameterize the SQL so it is protected from SQL injection exploits
cmd.CommandText = "select nocount from regn where pname=@pname And fname=@fname And dob=@dob"
cmd.Parameters.AddWithValue("@pname", PNAMETextBox.Text)
cmd.Parameters.AddWithValue("@fname", FNAMETextBox.Text)
cmd.Parameters.AddWithValue("@dob", DOBDateTimePicker.Text)
' Execute the SQL retuning the first column of the first row (e.g. the nocount from the query)
i = cmd.ExecuteScalar
End Using
正如@Tim Schmelter所指出的,这个命令是用Using包装的,当它被再次使用时,Using会正确地处理它,在我的示例中,我忽略了连接,假设它已在其他地方正确设置和处理。除了sql注入问题和缺少using语句之外,您的代码还有什么问题。当您说要填充值时。。。您的意思是要检索nocount的值,还是要插入或更新它的值,因为populate可以根据其使用方式指示所有这些情况?在上面的代码中,我看不到您在哪里初始化cmd,除非在该函数外部初始化,否则您可能会得到一个null引用。