2015-10-05 23 views
0

我有一个数据库在ms访问与表名regn。我想使用命令文本和执行器填充字段名称nocount。这里是我的代码:如何使用vb.net使用executioncaler从数据库填充值

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() 
+2

你的代码有什么问题(除了sql注入问题和缺少using语句)。 –

+0

当你说你想填充价值......你的意思是你想要检索nocount的价值,或者你想插入或更新它的价值(因为填充可以指示所有这些情况取决于它如何使用)?在上面的代码中,我没有看到你在初始化“cmd”的位置(大概你会得到一个空引用,除非它在该函数之外被初始化)。 –

回答

0

如果你显示你的变量i然后就可以看到从nocount第一值,其中通过你给出的条件被满足。

0

这假设你的连接是在其他地方设置的,看起来就像上面代码片段的情况。如果您只想获得“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 [email protected] And [email protected] And [email protected]" 
    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指出,这个命令是包裹着一个使用它正确时,它的完成被用于将处理它(再次,我忽略了我的例子中的连接,假设它在其他地方正确设置和处置)。

相关问题