Dim TableName As String
Dim ParamField As String
Dim ParamRecord As String
TableName = SearchBoxTableCmb.Text.ToString (the value for SearchBoxTableCmb.Text.ToString is "User")
ParamField = SearchBoxFieldCmb.Text.ToString (the value for SearchBoxFieldCmb.Text.ToString is "Username")
ParamRecord = SearchBoxTxt.Text (the value for SearchBoxTxt.Text is "Cshort")
Oledb.AddParam("@Table", TableName)
Oledb.AddParam("@Field", ParamField)
Oledb.AddParam("@Record", ParamRecord)
DataGrid.DataSource = Oledb.ExecQuery("SELECT * FROM @Table WHERE @Field LIKE @Record")
以下是名为Class
Imports System.Data.OleDb
Imports System.Data
Public Class OledbControl
Private OledbConn As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;" & _
"Data Source = '" & Application.StartupPath & "\AS_Service_Database.accdb'")
Private OledbCmd As New OleDbCommand
Public OledbDataAdap As New OleDbDataAdapter
Public OledbDataSet As New DataSet
Public Params As New List(Of OleDbParameter)
Public RecordCount As Integer
Public Exception As String
Public Function ExecQuery(Query As String) As Object
Try
OledbConn.Open()
OledbCmd = New OleDbCommand(Query, OledbConn)
Params.ForEach(Sub(x) OledbCmd.Parameters.Add(x))
Params.Clear()
OledbDataSet = New DataSet
OledbDataAdap = New OleDbDataAdapter(OledbCmd)
OledbDataAdap.Fill(OledbDataSet, "TableName")
Dim DataTable As DataTable = OledbDataSet.Tables("TableName")
ExecQuery = DataTable
OledbConn.Close()
Catch ex As Exception
Exception = ex.Message
End Try
If OledbConn.State = ConnectionState.Open Then OledbConn.Close()
End Function
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
结束班
我正在尝试使用文本框和一对组合框在数据库中进行搜索但是当我执行查询时它会创建异常消息 “查询中的语法错误。不完整的查询子句。”但我似乎无法找到查询错误的原因
答案 0 :(得分:3)
您无法将表名或列名绑定到参数。相反,使用从变量组合的动态查询,如下所示:
首先,我认为您需要使用新方法扩展您的Oledb类:
Public Sub AddParam(Name As String, Value As Object, type As OleDbType)
Dim NewParam As New OleDbParameter(Name, type)
NewParam.Value = Value
NewParam.Direction = ParameterDirection.Input
Params.Add(NewParam)
然后你需要调用它将OleDbType.VarChar作为类型
传递Dim TableName As String
Dim ParamField As String
Dim ParamRecord As String
TableName = SearchBoxTableCmb.Text.ToString
ParamField = SearchBoxFieldCmb.Text.ToString
ParamRecord = SearchBoxTxt.Text
'you can bind to the value only
Oledb.AddParam("@Record", ParamRecord, OleDbType.VarChar)
DataGrid.DataSource = Oledb.ExecQuery("SELECT * FROM [" & TableName & "] WHERE [" & ParamField & "] LIKE @Record")
答案 1 :(得分:1)
您需要使用string.Format()或类似的东西将字段和表值作为非参数值添加到字符串中。现在,您的查询输出将是
SELECT * FROM 'TABLE_VALUE' WHERE 'FIELD_VALUE' LIKE 'RECORD_VALUE'
确保在应用这些值时,您正在清理数据。
答案 2 :(得分:-2)
我相信你应该在引号之间加上你正在使用的参数LIKE:
DataGrid.DataSource = Oledb.ExecQuery("SELECT * FROM @Table WHERE @Field LIKE '@Record'")