简体   繁体   English

如何插入包含单引号或双引号的字符串

[英]How to insert string containing single or double quotes

If I want to insert a statement which contains quotation mark, how is it possible ? 如果我要插入包含引号的语句,怎么可能?

For Example I have a text box and I enter: 例如,我有一个文本框,然后输入:

Future Swami Vivekananda’s grand father's name was "____" .

If you use properly parameterized statements , you shouldn't need to worry about it. 如果使用正确的参数化语句 ,则无需担心。 Something like this (though please don't learn C# techniques from me): 像这样的东西(尽管请不要向我学习C#技术):

string sql = @"UPDATE dbo.table SET col = @p1 WHERE ...;";
string myString = @"hello'foo""bar";

SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
SqlParameter p1 = cmd.Parameters.AddWithValue("@p1", myString);
cmd.ExecuteNonQuery();

(Though you really should be using stored procedures.) (尽管您确实应该使用存储过程。)

If you are building your strings manually (which you really, really, really shouldn't be doing), you need to escape string delimiters by doubling them up: 如果您是手动构建字符串(实际上,实际上,实际上不应该这样做),则需要通过将它们加倍来转义字符串定界符:

INSERT dbo.tbl(col) VALUES('hello''foo"bar');

Use a parameterized query - then quotes don't matter at all . 使用参数化查询-那么行情并不重要 Also - your database doesn't get taken over by SQL injection - so win/win really. 另外-您的数据库不会被SQL注入所接管-因此,双赢确实如此。

You can double up the quote: 您可以将报价加倍:

INSERT INTO table
VALUES ('Future Swami Vivekananda''s grand father''s name was "____"')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何表达包含双引号而没有转义字符的字符串文字? - How to express a string literal containing double quotes without escape characters? 如何将包含双引号的字符串作为参数传递到BAT文件 - How to pass a string containing double quotes to a BAT file as an argument 字符串转义单引号内的双引号 - string escape double quotes inside single quotes 如何在c#中将包含单引号的字符串保存到Oracle DB - How to save string containing single quotes to Oracle DB in c# 使用包含双引号的字符串属性序列化对象 - Serializing an object with a string property containing double quotes 除非在单引号或双引号中,否则如何用空格分隔字符串 - How do I split a string by spaces except if in single or double quotes 如何在不将双引号更改为单引号的情况下将xml字符串更新到数据库中? - How to update an xml string into a database without changing from double quotes to single quotes? 将包含日期和时间的字符串替换为以 =(等号)为前缀的双引号 - Replacing the String containing Date and Time with Double Quotes prefixed with =(Equal Sign) 停止 Visual Studio 调试在包含双引号的字符串中放置斜杠 - Stop visual studio debug putting slash in string containing double quotes C#如何将日期字符串包装在字符串的双引号内的单引号中 - C# How to wrap date string in single quote inside the string's double quotes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM