伙计们,我想在vb中建立一个有效的搜索工具,以从我在mysql中存储了一些信息的段落的数据库中搜索数据。我希望搜索返回与google一样的多个结果,但在文本框中以相同概念的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
您已经自己回答了一个问题-如何进行子字符串搜索,只需在查询中添加%:
Dim sqlquery = "select text from text where name like '%" & TextBox1.Text & "%'"
(理想情况下,您可以使用参数化查询,而不是直接提供搜索值,这尤其有助于避免SQL注入。
至于第二部分-您已经在使用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类,这是连接多个字符串的有效方法。
PS不要忘记使用后关闭DataReader和Connection。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句