2011-04-06 66 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