在没有datagridview的情况下从vb中的文本框搜索/查询访问数据库

时间:2014-05-28 04:40:06

标签: vb.net search executenonquery

嘿伙计我需要一些帮助,从我的表单程序中执行基本搜索查询以连接到访问数据库。基本上我想学习如何点击我的查询按钮,搜索文本框中输入的文本,并根据找到的匹配项在另一个文本框中显示相应的数据。任何帮助将不胜感激。

这是我的查询按钮的代码到目前为止..

Private Sub btnQuery_Click(sender As Object, e As EventArgs) Handles btnQuery.Click

    con = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Eric\Documents\Fadv.accdb")

    con.Open()


    Dim id As Integer
    Dim SQL As String = "SELECT FirstName, NAME FROM info WHERE FirstName=" & txtFirstName.Text & ""

    Using cmd As New OleDbCommand(SQL, con)

        id = Val(InputBox("Enter Query Criteria"))

        MsgBox(SQL)
        cmd.ExecuteNonQuery()

        con.Close()

结束使用

我在尝试找出(连接字符串)时遇到了一些麻烦我不确定这是否是我必须在此处声明的内容是我的代码,任何指导都将非常感谢。

`Private Sub btnQuery_Click(sender as Object,e As EventArgs)处理btnQuery.Click

    Using con As New OleDbCommand(connectionstring)

        Dim cmd As New OleDbCommand(SQL, con)

        con.open()

        Dim reader As OleDbDataReader = cmd.ExecuteReader()

        While reader.Read()

            txtFirstName.Text = reader(0).ToString())

        End While

        reader.Close()

    End Using

`

1 个答案:

答案 0 :(得分:1)

ExecuteNonQuery()应该用于写入数据库,而不是从中读取。 “虽然ExecuteNonQuery没有返回任何行... []”,但MSDN Documentation表示。

有几种方法可以执行您要执行的操作。我建议查看示例here,因为它会向您展示如何使用OleDb执行查询。

要将查询中的数据提供给文本框,您可以执行以下操作:

Using con As New OleDbConnection(connectionstring) //Your connection string
    Dim command As New OleDbCommand(SQL, con) 

    connection.Open()

    Dim reader As OleDbDataReader = command.ExecuteReader()
    While reader.Read()
        TextBox1.Text = reader(0).ToString())
    End While
    reader.Close()
End Using 

This link提供了更多说明,如果您阅读了它的内容,将会对您有很大的帮助。具体做法是:

"You use the Read method of the DataReader object to obtain a row from the results of the query. You can access each column of the returned row by passing the name or ordinal reference of the column to the DataReader. However, for best performance, the DataReader provides a series of methods that allow you to access column values in their native data types (GetDateTime, GetDouble, GetGuid, GetInt32, and so on)."

另请注意:您希望对查询进行参数化。