简体   繁体   English

遇到包含撇号的名称(例如O'Conner)时执行查询时出错

[英]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.

相关问题 尽管在例如 Access 中工作,SQL 查询却没有提供任何结果? - SQL Query delivers no results despite working in e.g. Access? 与名称中包含撇号的名称匹配 - matching with name containing apostrophe in php 列名带有数字前缀(例如3name)是否合法? - Is it valid syntax to have a column name prefixed with a number, e.g., 3name? 可以在C ++平台上使用ADO来查询一系列记录吗? 例如,每个查询100条记录? - Can ADO on C++ platform be used to query a range of records? E.g. 100 records per query? 选择在单个值中包含混合字符的行,例如名称列中的“ Joh?n” - Select rows that has mixed charcters in a single value e.g. 'Joh?n' in name column 使用 sqlalchemy 执行查询时出现“无效对象名称”错误 - “Invalid object name” error when executing query using sqlalchemy SQL 长时间运行查询/最大化服务器资源,例如 RAM/CPU - SQL Long running query / maxing out server resource e.g. RAM/CPU SQL搜索查询多个Where子句,例如,名字和姓氏 - SQL Search Query for Multiple Where Clauses e.g. Firstname AND Surname 如何使用SQL查询获取Progress OpenEdge数据库信息,例如数据库版本 - How to use a SQL query to get the Progress OpenEdge database information, e.g. database version MySQL查询utf-8字符(例如中文)(另外,我使用的是Doctrine) - MySQL query utf-8 characters (e.g. Chinese)(Also, I am using Doctrine)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM