从数据库中搜索多个结果并在单个文本框中显示

时间:2013-10-04 16:25:35

标签: vb.net

伙计们我想在vb中构建一个高效的搜索工具来搜索mysql中我的数据库中的数据,其中我存储了一些信息的段落。我希望搜索返回多个结果,如谷歌,但在文本框中以2-3段相同的概念形式。为了使搜索更有效,我想包括子串功能,这是选择中的%符号查询。谁能告诉我如何实现这两个功能?这是我的基本搜索代码,它只将表格中存储的一个段落返回到我先隐藏的结果文本框中,然后显示结果出现的时间。

 If TextBox1.Text = "" Then
        MsgBox("Please Enter a Keyword")
    Else

        Dim conn As MySqlConnection
        conn = New MySqlConnection
        conn.ConnectionString = "Server=localhost;UserID=root;Password=admin674;Database=db1"
        Dim myadapter As New MySqlDataAdapter
        conn.Open()
        Dim sqlquery = "select text from text where name like '" & TextBox1.Text & "'"
        Dim mycommand As New MySqlCommand
        mycommand.Connection = conn
        mycommand.CommandText = sqlquery
        myadapter.SelectCommand = mycommand
        Dim mydata As MySqlDataReader
        mydata = mycommand.ExecuteReader
        If mydata.HasRows = 0 Then
            MsgBox("Data Not Found")
            TextBox1.Clear()
            TextBox2.Clear()

        Else
            mydata.Read()
            TextBox2.Text = mydata.Item("text")
            TextBox2.Show()


        End If

1 个答案:

答案 0 :(得分:1)

您已经自己回答了一个问题 - 如何进行子字符串搜索,简单地将%添加到您的查询中:

Dim sqlquery = "select text from text where name like '%" & TextBox1.Text & "%'"

(理想情况下,您可以使用parametrized query代替在线提供搜索值,这有助于避免SQL Injection

至于第二部分 - 您已经在使用DataReader,您只需使用单个mydata.Read()命令 - 循环其所有结果。取代

mydata.Read()
TextBox2.Text = mydata.Item("text")
TextBox2.Show()

Dim sb as New StringBuilder()

While mydata.Read()
   sb.AppendLine(mydata("text"))
End While

TextBox2.Text = sb.ToString()
TextBox2.Show()

这种方法使用StringBuilder class,这是连接多个字符串的有效方法。

P.S。使用后不要忘记关闭DataReader和Connection。

相关问题