I want to insert the String ' xxx'xxx ' in a field of a Table. The problem in the ' character. How i can insert this character?
3 Answers
You need to duplicate the single quote:
insert into foo (col_name)
values
('xxx''xxx');
But you should look into prepared statements which will not only make things like that a lot easier but will also protect you from SQL injection (I don't know C#, so I can't help you with the details).
double the single quote
if you are inserting directly,
INSERT INTO tableName (colName) VALUES ('xxx''xxx')
but if you are doing it on C#
, use parameterized query.
string connStr = "connection String here";
string val = "xxx'xxx";
string query = "INSERT INTO tableName (colName) VALUES (:val)";
using(NpgsqlConnection conn = new NpgsqlConnection(connStr))
{
using(NpgsqlCommand comm = new NpgsqlCommand())
{
comm.Connection = conn;
comm.CommandText = query;
NpgsqlParameter p = new NpgsqlParameter("val", NpgsqlDbType.Text);
p.value = val;
comm.Parameters.Add(p);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch(NpgsqlException e)
{
// do something with
// e.ToString();
}
}
}
-
-
@Sam1 i think
:
is also supported.John Woo– John Woo02/18/2013 14:28:20Commented Feb 18, 2013 at 14:28
In c# If you want to insert single quote you can do this by replacing original value so:
string x = "xxx'xxx";
string replacedText = x.Replace("'","''");
and when inserting to prevent from sql injection always use Parameters:
myCommand.CommandText = "INSERT INTO TableName (x) VALUES (@x)";
myCommand.Parameters.Add("@x", x);