【问题标题】:SQL search query to Access DB?访问数据库的 SQL 搜索查询?
【发布时间】:2013-01-08 03:35:21
【问题描述】:

我正在尝试使用文本框中的搜索按钮查询 Access 数据库并将结果插入到列表框中。这是我到目前为止的代码:

    Dim con As New OleDbConnection(DBcon)
    Try
        lbresults.Items.Clear()
        Dim dr As OleDbDataReader
        Dim command As New OleDbCommand("Select I.InstName, S.StuName FROM Instructor I, Student S WHERE I.InstName Like '%" & txtsearch.Text & "%' and S.StuName like '%" & txtsearch.Text & "%'", con)

        con.Open()

        command.Connection = con
        dr = command.ExecuteReader

        While dr.Read()
            lbresults.Items.Add(dr("InstName"))
            lbresults.Items.Add(dr("StuName"))
        End While

    Catch ex As Exception

我遇到的问题是它在列表框中多次返回 InstName 和 StuName。我猜这是因为我正在做 items.add 两次?我试图使用“[oledbcommand 变量名].parameters.addwithvalue”,但我不知道如何使用“like”函数。

【问题讨论】:

    标签: sql vb.net visual-studio-2010


    【解决方案1】:

    如果将 InstName 和 StuName 多次添加到下拉列表中,可能是因为查询多次返回记录,因为您正在执行 select ... where ... like...

    尝试将您的选择语句更改为(注意单词 DISTINCT):

    Dim command As New OleDbCommand("Select DISTINCT I.InstName, S.StuName FROM Instructor I, Student S WHERE I.InstName Like '%" & txtsearch.Text & "%' and S.StuName like '%" & txtsearch.Text & "%'", con)
    

    【讨论】:

      【解决方案2】:

      您的查询是关联两个表但未指定关系。

      给猫剥皮有多种方法,但我会这样做以保证我能控制结果:

      dim SQL as new string = _
          "Select 'Instructor' as NameType, I.InstName as NameValue " _
          "from Instructor I " _
          "where I.InstName Like '%" & txtsearch.Text & "%' " & _
          "union " & _
          "Select 'Student' as NameType, S.StuName as NameValue " _
          "from Student  S " _
          "where S.StuName Like '%" & txtsearch.Text & "%' " 
      
      Dim command As New OleDbCommand(SQL, con)
      

      使用 union 与 union all 会在数据集中返回不同的记录,如果出现重复名称,instructor 是主要的表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-25
        • 1970-01-01
        • 2021-12-12
        • 2021-04-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-25
        相关资源
        最近更新 更多