[英]Insert into statement with an apostophe using VBA?
I have a form with textboxes.我有一个带有文本框的表单。 I am inserting what the user enters into the textbox into a table.
我将用户在文本框中输入的内容插入到表格中。 If the user enters an apostrophe in the textbox labeled "Me.ProjectName", I get an error.
如果用户在标记为“Me.ProjectName”的文本框中输入撇号,我会收到错误消息。 My code is:
我的代码是:
CurrentDb.Execute "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Me.ProjectName & "')"
You should not construct and execute dynamic SQL based on user input.不应根据用户输入构造和执行动态 SQL 。 You should use a parameterized query , something like:
您应该使用参数化查询,例如:
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
You should escape your strings possibly containing quotes by replacing a quote with 2 quotes:您应该通过用 2 个引号替换引号来转义可能包含引号的字符串:
Dim SQL As String
SQL = "INSERT INTO Table1(ProjectNumber, Title) " & _
" VALUES('" & ProjectNumber & "','" & Replace(Me.ProjectName, "'", "''") & "')"
CurrentDb.Execute SQL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.