如何插入包含撇号(单引号)的值? [英] How to insert a value that contains an apostrophe (single quote)?

查看:38
本文介绍了如何插入包含撇号(单引号)的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

插入带有撇号的值的正确 SQL 语法是什么?

What is the correct SQL syntax to insert a value with an apostrophe in it?

Insert into Person
  (First, Last)
Values
  'Joe',
  'O'Brien'

我不断收到错误消息,因为我认为 O 后面的撇号是该值的结束标记.

I keep getting an error as I think the apostrophe after the O is the ending tag for the value.

推荐答案

在 SQL 中转义撇号(即双引号):

Escape the apostrophe (i.e. double-up the single quote character) in your SQL:

INSERT INTO Person
    (First, Last)
VALUES
    ('Joe', 'O''Brien')
              /\
          right here  

这同样适用于 SELECT 查询:

The same applies to SELECT queries:

SELECT First, Last FROM Person WHERE Last = 'O''Brien'


撇号或单引号是 SQL 中的特殊字符,用于指定字符串数据的开头和结尾.这意味着要将其用作文字字符串数据的一部分,您需要 escape 特殊字符.对于单引号,这通常是通过将您的报价加倍来实现的.(两个单引号字符,不是双引号而是单引号.)


The apostrophe, or single quote, is a special character in SQL that specifies the beginning and end of string data. This means that to use it as part of your literal string data you need to escape the special character. With a single quote this is typically accomplished by doubling your quote. (Two single quote characters, not double-quote instead of a single quote.)

注意:您应该只在通过原始 SQL 界面手动编辑数据时担心这个问题,因为在开发和测试之外编写查询应该很少发生.在代码中,有一些技术和框架(取决于您的堆栈)负责转义特殊字符,SQL 注入

Note: You should only ever worry about this issue when you manually edit data via a raw SQL interface since writing queries outside of development and testing should be a rare occurrence. In code there are techniques and frameworks (depending on your stack) that take care of escaping special characters, SQL injection, etc.

这篇关于如何插入包含撇号(单引号)的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆