2011-04-06 64 views
0

我有一個程序,它將從數據庫(MS Access 2007)中找到一個記錄,其中含有一個錯誤:查詢表達式中的語法錯誤'%1%'的名字出錯'VB6查找問題使用SQL(MS Access 2007)

這是我的代碼:

Dim find As String 

find = txtfind.Text 

If txtfind.Text <> "" Then 
    Set rs = db.OpenRecordset("SELECT * from records WHERE firstname like '*'" & find & "'*") 

    If rs.EOF = True Then 
     MsgBox "No Record Found!", vbCritical + vbOKOnly, "Error" 
    Else 
     Text1 = rs(0) 
     Text2 = rs(1) 
     Text3 = rs(2) 
     Text4 = rs(3) 
    End If 

    If Not rs Is Nothing Then 
     Set rs = Nothing 
    Else 
     rs.Close 
    End If 

End If 
+0

是不是訪問通配符'*'而不是'%'? – 2011-04-06 09:17:44

+2

這樣:''從記錄WHERE firstname'*'「&find&」'*「'的SELECT *將產生'SELECT *從記錄WHERE firstname like'*'1''。我相信它應該是''SELECT *從記錄WHERE名字像'*「&find&」*'「'(注意我刪除了一個** **並且改變了另一個的位置)。 – ssarabando 2011-04-06 09:31:48

+1

你在'WHERE'子句中防範SQL注入嗎?請參閱http://stackoverflow.com/questions/512174/non-web-sql-injection/515150#515150 – onedaywhen 2011-04-06 15:08:30

回答

0

通配符的訪問是*不是%。

請以下嘗試:

Set rs = db.OpenRecordset("SELECT * from records WHERE firstname like '*" & find & "*'") 

此外,在接入使用通配符全面的資源:

10 tips for using wildcard characters in Microsoft Access

希望幫助!

+0

如何編輯我的代碼?我在代碼的語法方面有錯誤... – 2011-04-06 09:26:14

+0

更新了原始答案。希望有所幫助。 試試這個:Set rs = db.OpenRecordset(「SELECT * from WHERE firstname like'\ *」&find&「\ *'」) 單引號應出現在第一個\ *字符之前,第二個之後\ *字符,不在中間。 – Vaibhav 2011-04-06 09:31:58

+0

閱讀你的「資源」,發現「Access的通配符是*不是%」是一個錯誤陳述。綜合資源?它沒有提到'ALIKE'關鍵字。請參閱http://stackoverflow.com/questions/5166907/ms-access-sql-any-reason-why-like-does-not-work/5170214#5170214另外,我看不到提及的事實,因爲Access2003 UI可以放置在ANSI-92查詢模式中。 – onedaywhen 2011-04-06 15:05:58