现有数据库检查vb.net

时间:2015-02-12 09:52:00

标签: vb.net

我只想简单检查一下我的数据库中是否有现有记录。我收到此错误消息:

  

ExecuteReader:尚未初始化Connection属性。

Dim con As New SqlConnection
Dim str As String
str = "SELECT * FROM test1 WHERE voornaam= & txtfirstname.Text"
Dim cmd As SqlCommand = New SqlCommand(Str)
Dim dr As SqlDataReader

con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\database test\ikeagoed\ikeagoed\test.mdf;Integrated Security=True"


con.Open()
dr = cmd.ExecuteReader
dr.Read()

If txtfirstname.Text = dr("voornaam").ToString Then
    MsgBox("exist")
Else
    MsgBox("doesn't exist")
End If
con.Close()

2 个答案:

答案 0 :(得分:0)

根据错误,您需要初始化SqlCommand上的连接属性。您可以通过修改对构造函数的调用来执行此操作:

Dim cmd As SqlCommand = New SqlCommand(Str, con) 'include connection parameter

或通过在施工后设置属性

Dim cmd As SqlCommand = New SqlCommand(Str)
cmd.Connection = con

这将使您超越第一个问题,但您的代码还有其他问题 - 您将文本框值分配到sql命令的方式不正确。您需要按以下方式执行此操作:

Dim str As String
str = "SELECT * FROM test1 WHERE voornaam='" & txtfirstname.Text & "'"

但是这导致了SQL Injection的区域。请注意it can cause的内容并确保您防范它 - 这个区域太大,无法详细介绍。

答案 1 :(得分:0)

就像这样

 Dim con As New SqlConnection

con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\database test\ikeagoed\ikeagoed\test.mdf;Integrated Security=True"

con.open()
Dim str As String
str = "SELECT * FROM test1 WHERE voornaam= & txtfirstname.Text"
Dim cmd As New SqlCommand(Str,con)
Dim dr As SqlDataReader = cmd.ExecuteReader


If dr.Read() Then

    MsgBox("exist")

Else

    MsgBox("doesn't exist")


End If
dr.close()
con.Close()