[英]Error executing query when encountering name containing an apostrophe (e.g. O'Conner)
My database program has a statement like: 我的数据库程序具有如下语句:
variable = "SELECT * from Staff where StaffName = '" & cStaffName & "'"
This works fine until I have a member of staff with ' (apostrophe) in there name as it ends the start apostrophe. 直到我有一个名字中带有'(撇号)的工作人员为止,此方法才能正常工作,因为它结束了开始的撇号。
SELECT * from Staff where StaffName = 'O'Conner'
Is there a way around this without replacing the apostrophe in her name? 有没有办法解决这个问题而不用她的名字代替撇号?
You just need to use a parameterized query. 您只需要使用参数化查询。
Using con = new SqlConnection(....)
Using cmd = new SqlCommand("SELECT * from Staff where StaffName = @name", con)
con.Open
cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = cStaffName
Using reader = cmd.ExecuteReader
.....
End Using
End Using
End Using
In this scenario you add a parameter to the SqlCommand parameters collection. 在这种情况下,您将一个参数添加到SqlCommand参数集合中。 The command text has no more a string concatenation but contains a parameter placeholder (@name). 命令文本不再具有字符串连接,而是包含参数占位符(@name)。 The parameter itself contains the value you want to pass to your query. 参数本身包含您要传递给查询的值。 In this way there is no problem with quotes embedded in the value. 这样,值中嵌入的引号就没有问题。
You also get the extra benefit to avoid any kind of Sql Injection problem with the user input 您还将获得额外的好处,以避免用户输入出现任何类型的Sql Injection问题
variable = "SELECT * from Staff where StaffName = '" & Replace(cStaffName, "'", "\'") & "'"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.