single quotes escape during string insertion into a database

♀尐吖头ヾ 提交于 2019-11-27 04:23:21

问题


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.

textBox3.Text.Replace("'", " \'");
string sql= "insert into gtable (1text,1memo) values ('"+textBox3.Text+"',null)";
        OleDbCommand cmd = new OleDbCommand(sql, con);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

I did have the option of replacing "'" with "`" but this changes the text in the db as well. I wish to retain "'" as the same , and also insert it into the db.


回答1:


try

string sql= "insert into gtable (1text, 1memo) " + 
            "values ('" + textBox3.Text.Replace("'", "''") + "', null)";



回答2:


Try this

    string sql= "insert into gtable (1text,1memo) values (@col1,NULL)";
    OleDbCommand cmd = new OleDbCommand(sql, con);
    cmd.Parameters.AddWithValue("@col1",textBox3.Text);
    con.Open();



回答3:


To insert single quotes in database replace ' with ''. In database only single quote will go.

Use this

string sql= "insert into gtable (1text,1memo) values ('" 
            + textBox3.Text.Replace("'", "''") + "', null)";

Rest code is same.




回答4:


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



回答5:


The best way is:

string Name = Server.HtmlEncode(txtName.Text);


来源:https://stackoverflow.com/questions/11912412/single-quotes-escape-during-string-insertion-into-a-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!