我有一个带有文本框的表单。我将用户输入文本框的内容插入到表中。如果用户在标有" Me.ProjectName"的文本框中输入撇号,则会出错。我的代码是:
CurrentDb.Execute "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Me.ProjectName & "')"
答案 0 :(得分:4)
您不应根据用户输入构建和执行动态SQL 。您应该使用参数化查询,例如:
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = cdb.CreateQueryDef("", _
"INSERT INTO Table1 (ProjectNumber, Title) VALUES (@prjnum, @title)")
qdf.Parameters("@prjnum").Value = ProjectNumber
qdf.Parameters("@title").Value = me.ProjectName
qdf.Execute
答案 1 :(得分:1)
你应该 逃避 你的字符串可能包含引号,方法是用2引号替换引号:
Dim SQL As String
SQL = "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Replace(Me.ProjectName, "'", "''") & "')"
CurrentDb.Execute SQL