Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Try
' Dim i As Integer
Dim sql As String
Dim cmd As New OleDb.OleDbCommand
conn.Open()
sql = “Select * from tblBooks where AUTHOR like '" & TextBox1.Text & "'"
cmd.Connection = conn
cmd.CommandText = sql
Catch ex As Exception
MsgBox(ex.Message)
Finally
conn.Close()
End Try
End Sub
我的搜索按鈕目前看起來像這樣。我很感激任何幫助
uj5u.com熱心網友回復:
不要在使用它們的方法之外宣告連接。連接、命令和 DataReader 有一個Dispose方法,必須呼叫該方法才能釋放非托管資源。該語言提供了Using用于關閉和處理這些物件的塊。
永遠不要連接字串來構建 sql 字串。始終使用引數來避免 sql 注入。
您設定了一個命令,但從未執行過它,即使您確實執行了它,您也沒有提供任何方式來顯示回傳值。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Dim sql = "Select * from tblBooks where AUTHOR like @Author;"
Try
Using conn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("@Author", OleDbType.VarChar).Value = $"*{TextBox1.Text}*"
conn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using 'Closes and disposes reader
End Using 'Closes and disposes connection and disposes command
DataGridView1.DataSource = dt
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
uj5u.com熱心網友回復:
按原樣,它只會回傳完全匹配。嘗試添加通配符:
sql = "Select * from tblBooks where AUTHOR like '*" & TextBox1.Text & "*'"
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/374992.html
