1

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?

1
  • Why the close votes, this is a simple, straightforward and valid question with simple answers. Commented Feb 19, 2013 at 3:23

3 Answers 3

4

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

1

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();
        }
    }
}
2
  • (:val) <- shouldnt that be @val Commented Feb 18, 2013 at 14:26
  • @Sam1 i think : is also supported. Commented Feb 18, 2013 at 14:28
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.