开发者

how to add ' like special characters in mysql varchar data type column?

开发者 https://www.devze.com 2023-03-21 20:58 出处:网络
I am trying to insert str开发者_开发百科ing as \"baby\'s world\" into the column of type varchar through query but shows me error.

I am trying to insert str开发者_开发百科ing as "baby's world" into the column of type varchar through query but shows me error. Is there anything else i need to put to the query so that it accept that symbol


put a backslash in front of it like so:

"Baby\'s world"

You can find and replace them in your string using the following:

str.Replace('\'', '\\\'')

I'm not 100% sure about this last part, but you need to 'escape' the ' and \ by adding a \ in front of it. So it would seem alright (can't test as i'm not a C# programmer.


Since you are asking about Visual Studio (.NET), you need to use parameterized query. Don't use concatenation when constructing query

private void PrepareExample()
{
    string s = Console.ReadLine();
    MySqlCommand cmd = new MySqlCommand("INSERT INTO movie(title) VALUES (?title)", myConnection);
    cmd.Parameters.AddWithValue( "?title", "baby's world" );
    cmd.Prepare();
    cmd.ExecuteNonQuery();
}

Or

private void PrepareExample()
{
    MySqlCommand cmd = new MySqlCommand("INSERT INTO movie(title) VALUES (?title)", myConnection);
    // try to input: baby's world. or try: baby"s world. everything are ok :-)
    cmd.Parameters.AddWithValue( "?title", Console.ReadLine() ); 
    cmd.Prepare();
    cmd.ExecuteNonQuery();
}

Though this is not exactly concatenation, don't use this:

qry = string.Format("INSERT INTO movie(title) VALUES("{0}", Console.ReadLine());

Though if you really found a need to run SQL that way, replace single quote with backslash

qry = string.Format("INSERT INTO movie(title) VALUES("{0}", 
              Console.ReadLine().Replace("'", "\'");

But do consider using parameterized query instead of concatenation or string.Format, as parameterized query automatically take care of those delimeter nuances.

http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html


Just use mysql_real_escape_string(). There is no need to do anything else.

For example:

mysql_real_escape_string($user),
mysql_real_escape_string($password));


INSERT INTO table (field) VALUES ('baby's world') will fail because the string is truncated to INSERT INTO table (field) VALUES ('baby' and the rest is seen as invalid code.

There are two ways to stop this, the second being advisable for good practice coding:

INSERT INTO table (field) VALUES ("baby's world")

INSERT INTO table (field) VAUES ('baby\'s world')

0

精彩评论

暂无评论...
验证码 换一张
取 消