-1

我希望 VB 中的代码检查数据库中的值是否存在。

这是我的代码

conn.open()
Dim select As New OleDbCommand

select.Connection = conn

select.CommandText = " SELECT COUNT(*) FROM your_table WHERE field = textbox.value"
if count>0
MsgBox("already exists")

conn.close()

但它不工作。

4

3 回答 3

1

您的查询是错误的,您没有以这种方式将文本框值放入查询中。
您应该始终使用参数化查询

Dim commandText = "SELECT count(*) from your_table where field = ?"
Using(conn = new OleDbConnection(.....)
Using(select = New OleDbCommand(commandText, conn)
    conn.open()
    select.Parameters.Add("@p1", textbox.value)
    Dim count = Convert.ToInt32(select.ExecuteScalar())
    if count > 0 Then
        MsgBox(" already exsist ")
    End If
End Using
End Using

在这里,您在命令文本中设置参数占位符 (?),并将参数及其值添加到命令中。之后,您需要执行命令。在您的情况下,您只需要一个值作为命令的返回值,因此 ExecuteScalar 是正确使用的方法。

另请注意,连接和命令是一次性对象,因此当您不再需要它们时应该关闭并丢弃它们。为此,正确的方法是使用语句

于 2013-09-15T12:34:38.670 回答
0

Your query is not correct

"SELECT COUNT(*) FROM your_table WHERE field = textbox.value"

Change it to

"SELECT COUNT(*) FROM your_table WHERE field = '" & textbox.text & "'"

1) Winforms TextBox control dose not have a Value property. it has text property ( I am assuming you are using Textbox control)

2) You need to send the value contained in the Textbox.Text and not "TextBox.Value". Hence you have add two string as mentioned in new query

3) Then & endif is missing in your if statement

4) This is not the correct way to use the query as mentioned by @steve and others.

于 2013-09-15T14:06:02.077 回答
0

这工作正常。

Public Sub insrt()
    con.Open()

    Dim cmd1 As New OleDbCommand("select count(*) from tbcat where catname=?", con)
    cmd1.Parameters.Add("@cat", OleDbType.VarChar).Value = txtcourse.Text
    Dim count = Convert.ToInt32(cmd1.ExecuteScalar)
    If count > 0 Then
        MsgBox("Already Exist")
        'Exit Sub
    Else
        Dim cmd As New OleDbCommand("insert into tbCat(Catcode,catname,protype)values('" & txtcode.Text & "','" & txtcourse.Text & "','" & txttype.Text & "')", con)
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        'con.Close()
        display_course()

        txtcode.Text = String.Empty
        txtcourse.Text = String.Empty
    End If
    cmd1.Dispose()
    con.Close()
End Sub
于 2017-05-25T04:30:05.410 回答