user123456 user123456 - 1 year ago 74
SQL Question

Cannot insert text having ' (apostrophe) into SQL Server table

I'm trying to insert text into a SQL table using a textbox:

SqlCommand cmd = new SqlCommand("INSERT INTO Book(Title) VALUES ('" + textBoxTitle.Text + "','" +
"')", conn);

But if text contains apostrophe (ex. You'll...), it's showing:
Incorrect syntax near 'll'.

Answer Source

First of all, you have two values in your VALUES part. One is textBoxTitle.Text and the other one is ''. But you provided just one column.

If that's true, you should delete '' part in your query. But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

If parameterized queries and statements creates any problem with single quote, use double single quotes for each.

Also use using statement to dispose your database connections and commands.

using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cmd = con.CreateCommand())
    cmd.CommandText = "INSERT INTO Book(Title) VALUES (@title)";
    cmd.Parameters.AddWithValue("@title", textBoxTitle.Text);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download