Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

single quotes escape during string insertion into a database

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.

like image 655
lunchbox Avatar asked Aug 11 '12 06:08

lunchbox


People also ask

How do you escape a single quote in an inserted statement?

Because a single quote is used for indicating the start and end of a string; you need to escape it. The short answer is to use two single quotes - '' - in order for an SQL database to store the value as ' .

How do you escape a single quote in SQL query string?

The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.

Can you use single quotes in SQL?

Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren't used in SQL, but that can vary from database to database. Stick to using single quotes. That's the primary use anyway.


1 Answers

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(); 
like image 85
codingbiz Avatar answered Sep 23 '22 09:09

codingbiz