single quotes escape during string insertion into a database

前端 未结 5 2041
不思量自难忘°
不思量自难忘° 2020-12-05 07:11

Insertion fails when \"\'\" is used. example string is: He\'s is a boy. I\'ve attempted to skip the \"\'\" using an escape symbol , but I believe this is not the right way.<

5条回答
  •  天命终不由人
    2020-12-05 07:42

    On the MSDN article for String.Replace it says:

    Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.

    On the very first line you are not assigning the value of textBox3.Text to the result of that method call, meaning that absolutely nothing happens.

    Furthermore, to escape a quote in SQL Server, you simply use two single-quotes (Note: NOT the same thing as a double-quote).

    This should give you the expected outcome:

    textBox3.Text = textBox3.Text.Replace("'", "''");
    

    Additionally, you may wish to look into String.Format for your string concatenation needs.

    String escapedInput = textBox3.Text.Replace("'", "''");
    String sql = String.Format("insert into gtable (1text,1memo) values ('{0}',null)", escapedInput);
    

提交回复
热议问题