简体   繁体   中英

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):

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.

You can double up the quote:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM