VB SQL ACCESS选择Where语句

时间:2014-03-30 20:15:25

标签: sql vb.net

Net,我正在尝试学习如何在搜索按钮作为查询的触发事件时将查询结果显示到数据网格中。 但是当我点击搜索按钮但没有给我发生错误消息(请参阅错误消息的屏幕截图的链接),我不明白。

错误:http://s1.postimg.org/di091riv3/error1.jpg

请你指出正确的方向,谢谢。

以下是我的代码

Imports System.Data.OleDb

Public Class SearchForm
    Dim con As New OleDbConnection



    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Statd.SelectedIndexChanged

    End Sub


    Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click

        con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
        con.Open()


        Dim sqlQuery As String
        Dim sqlCommand As New OleDbCommand
        Dim sqlAdapter As New OleDbDataAdapter
        Dim Table As New DataTable
        Dim empNum As String
        Dim empLname As String
        Dim empDept As String
        Dim empStat As String


        empNum = eNumText.Text
        empLname = empLnameText.Text
        empDept = Deptd.Text
        empStat = Statd.Text

        sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '% " & empLnameText.Text & "' "

        ' MsgBox("Employee Number " + empNum + empLname + empDept + empStat) 'test statement 


        With sqlCommand
            .CommandText = sqlQuery
            .Connection = con

            With sqlAdapter
                .SelectCommand = sqlCommand
                .Fill(Table)

            End With

            For i = 0 To Table.Rows.Count - 1
                With DataGridView1
                    .Rows.Add(Table.Rows(i)("EmpID"), Table.Rows(i)("FirstName"), Table.Rows(i)("LastName"), Table.Rows(i)("Department"), Table.Rows(i)("Position"), Table.Rows(i)("Status"), Table.Rows(i)("Years"))

                End With
            Next


        End With






        con.Close()
    End Sub

3 个答案:

答案 0 :(得分:0)

Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
    sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '%' + ? + '%' "

    'It's counter-intuitive, but it's best in .Net to use a new connection object each time
    Using con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"), _
          cmd As New OleDbCommand(sqlQuery, con)

        'Use actual column type and length here
        cmd.Parameters.Add("?", OleDbType.NVarChar, 50).Value = empLnameText.Text

        con.Open()
        DataGridView1.DataSource = cmd.ExecuteReader()
    End Using
End Sub

答案 1 :(得分:0)

尝试将查询中的%更改为*,如下所示:

sqlQuery = "SELECT * FROM tbl_empinfo WHERE LastName like '* " & empLnameText.Text & "' "

访问权限不会将%用作wildcard

http://www.techonthenet.com/access/queries/like.php

答案 2 :(得分:0)

我发现%的使用错误。它用于SQL Server和Not Access SQL使用*代替%