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'.
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.
How do I escape a single quote in SQL Server?
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);
con.Open();
cmd.ExecuteNonQuery();
}
As an alternative if you are programming .Net you can use SqlBulkCopy to insert your data without escaping any characters.
https://msdn.microsoft.com/en-us/library/ex21zs8x(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
As a bonus it is fast (faster than INSERT if you have a lot to insert).
Related
Hello i have a table called Card_tbl with a cell CardID. The problem is that when i insert only numbers like 12345 they are uploaded in the database, but when i use mix letters like Q1234R it will say INVALID COLUMN NAME Q1234R I tried many things to fix it but no success.
THE CELL IS ON VARCHAR(50) this is my code
Con.Open();
SqlCommand cmd = new SqlCommand("insert into Card_tbl values(" +txtCardNumber.Text+")", Con);
cmd.ExecuteNonQuery();
MessageBox.Show("Admin Successfully Added!");
Con.Close();
populate();
//updateroomstate();
Clean();
the error is shown here cmd.ExecuteNonQuery();
Thank you in advance.
Solution
The correct solution is to use prepared statements. You've said the column is a varchar(50) so:
using (SqlConnection conn = new SqlConnection("yourconnectionstring"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Card_tbl VALUES (#cardNumber)", conn))
{
// we specify type VarChar and size 50, because your column is a varchar(50)
cmd.Parameters.Add("#cardNumber", SqlDbType.VarChar, 50).Value = txtCardNumber.Text;
cmd.ExecuteNonQuery();
}
}
I would also recommend that you specify the column name for the insert:
INSERT INTO Card_tbl (CardId) VALUES (#cardNumber) -- I've assumed that the column is called CardId
Why do we need parameterized queries / prepared statements?
The reason we need prepared statements is because the user could enter something malicious in the query, forcing your server to execute queries that you didn't intend.
If you have a query like this, SQL Server will do the insert and then drop the table:
INSERT INTO MyTable VALUES ('hello'); DROP TABLE MyTable; -- comment
This is a multi-statement query, meaning that the INSERT will be done first, and then the DROP TABLE will be executed. The -- denotes a comment, and everything after that in the query is discarded.
Now, if you build a query like "INSERT INTO MyTable VALUES ('" + someUserInput + "')", how could a malicious user make this query more like the previous one? Simple: enter SQL into their input.
Suppose someUserInput is '); DROP TABLE MyTable; -- comment then your query will become:
INSERT INTO MyTable VALUES(''); DROP TABLE MyTable; -- comment')
Like this, a malicious user can perform an extremely destructive operation on your database, bypass login pages, expose secret information, etc. This is a huge risk for your application.
Prepared statements work by separating the query text from the parameter values. Because they're not part of the query, they can't be interpreted as SQL. It also means that binary data types can be sent to the server as binary rather than as text. Example: DateTime.
Try this instead
Insert into Card_tbl(CardID) values('" +txtCardNumber.Text+"')"
https://www.w3schools.com/sql/sql_insert.asp
If I want to insert a statement which contains quotation mark, how is it possible ?
For Example I have a text box and I enter:
Future Swami Vivekananda’s grand father's name was "____" .
If you use properly parameterized statements, you shouldn't need to worry about it. Something like this (though please don't learn C# techniques from me):
string sql = #"UPDATE dbo.table SET col = #p1 WHERE ...;";
string myString = #"hello'foo""bar";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#p1", SqlDbType.VarChar, 30).Value = myString;
(Though you really should be using stored procedures.)
If you are building your strings manually (which you really, really, really shouldn't be doing), you need to escape string delimiters by doubling them up:
INSERT dbo.tbl(col) VALUES('hello''foo"bar');
Use a parameterized query - then quotes don't matter at all. Also - your database doesn't get taken over by SQL injection - so win/win really.
You can double up the quote:
INSERT INTO table
VALUES ('Future Swami Vivekananda''s grand father''s name was "____"')
I am storing data (approx. 1500 words) in SQL server 2005 through textbox and button. I am using this code.
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
String query = String.Format("insert into try (data,sno) values ('{0}',22)",TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
Label1.Text = "submitted";
conn.Close();
}
I have column 'data' of data type 'char(4000)'.
Problem is that, when I store 1st paragraph (approx 1500 words), it stored successfully. But when I stored another paragraph (approx 1500 words), it show me the error.
"Incorrect syntax near 's'. Unclosed quotation mark after the
character string ',22)'."
What is the problem ??
Use Parameters
String query = "insert into try (data,sno) values (#data,22)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#data", TextBox1.text);
cmd.ExecuteNonQuery();
In this way you don't need to worry about the presence of single quotes in your text and, the most important thing, you avoid SqlInjection Attacks
String.Format will not escape the input string suitably for use in an SQL statement, which will lead to errors & serious vulnerabilities.
You should use Parameterized Queries which are designed specifically to address this.
This sounds like you have an ', or multiple 's, in the TextBox1.Text. You will need to replace all single quotes for double.
String query = String.Format("insert into try (data,sno) values ('{0}',22)",Replace(TextBox1.Text,"'","''"));
However, this approach will open you up to SQL Injection attacks. I'd recommend using a Stored Procedure, like the following:
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spInsertDataIntoTry";
cmd.Parameters.AddWithValue("#data", TextBox.Text);
cmd.ExecuteNonQuery();
Otherwise, you could use Parameters like others have mentioned.
Does your text contains ' letter? If yes then it is breaking INSERT query.
If you would try to insert following text:
Hello' there
Then your query would look like this:
insert into try (data,sno) values ('Hello' there,22)
Which results in incorrect query.
This is not the way queries should be done, because it leads to security issues (read more: SQL Injection) you should use parametrized queries.
"Incorrect syntax near 's' - this indicates your sql statements is wrong.
i guess that your input content maybe contains sql server keywords, so check your 2nd paragraph is there any keyword such as "'".
for example:
2nd paragraph is: how's the weather? it's cool!!!!!!!
so the sql statement is: insert into try (data,sno) values ('how's the weather? it's cool!!!!!!!',22)
it will arise an exception incorrect syntax near 's'
option 1: in this values are inserted using parameters
string insertstr = "INSERT INTO table_name(eid, eName, Dept) " +
"VALUES(#eid, #eName, #dept)";
SqlCommand cmd = new SqlCommand(insertstr, con);
cmd.Parameters.Add("#eid", SqlDbType.Int).Value = Convert.ToInt32(textBox1.Text);
cmd.Parameters.Add("#ename", SqlDbType.VarChar, 50).Value = textBox2.Text.ToString();
cmd.Parameters.Add("#dept", SqlDbType.VarChar, 100).Value = textBox3.Text.ToString();
Option 2:
SqlCommand cmd = new SqlCommand("INSERT INTO table_name(eid,eName,Dept) values('"+ textBox1.Text +"','"+ textBox2.Text +"','"+ Textbox3.Text +"'", con);
cmd.ExecuteNonQuery();
Most of the projects i had seen the 1st option... what is the use of passing values using parameters?? any advantages by passing values using parameters?? your suggestion plz..
You don't have to care about quoting special characters. If you forget to quote a SQL-Injection attack is possible.
If you use Option 2 and one enters the following into Textbox3
'); DELETE * FROM table_name; --
the following SQL statements are excecuted:
INSERT INTO table_name(eid,eName,Dept) values ('value1','value2','');
DELETE * FROM table_name; -- ')
The second statement deletes every row from table_name. Instead of a delete statement any possible statement could be inserted there.
Several reasons:
You don't have to worry to escape special characters (like ') to avoid SQL errors or SQL injections (as explained by H-Man2).
You don't have to worry to transform C# types to SQL types. For instance:
If your NumberDecimalSeparator is equal to the comma , and you want to insert a Double value in your database, you normally have to replace the comma by a point. No need to worry about that with parameters.
No need to worry about DateTime formats neither.
...
I find also the code more readable and easier to maintain with parameters when your SQL queries start to have a great length.
You should NEVER use option 2.
This is very bad practise, and very open to SQL Injection.
Always stick with Option 1. This is the best option by far.
Read here for more information on SQL Injection:
http://en.wikipedia.org/wiki/SQL_injection
For example, this is the code that I am using:
String commandString = "UPDATE Members SET UserName = #newName , AdminLevel = #userLevel WHERE UserID = #userid";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnectionstring"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(commandString, conn);
cmd.Parameters.Add("#newName", newName);
cmd.Parameters.Add("#userLevel", userLevel);
cmd.Parameters.Add("#userid", userid);
conn.Open();
cmd.ExecuteReader();
Reader.Close();
}
That code looks fine. Parameterisation is the way to go, as opposed to concatenating user-supplied values in an adhoc SQL statement which can open you up to sql injection attacks. This can also help with execution plan reuse.
The only thing I'd add, is I prefer to explicitly define the datatype and sizes of the parameters. For example, if you don't then, as an example, all string values will get passed in to the database as NVARCHAR instead of VARCHAR. Hence I like to be explicit.
It's safe against SQL injection because it's parameterized. Other security concerns, such as ensuring that #userid is not spoofed, are separate security concerns that should be dealt with in other layers of your application.
That's still a static query string. It's not really "dynamic" sql until you also build parts of the string on the fly — something like this:
var sql = "SELECT columns FROM Table WHERE 1=1";
if (!string.IsNullOrEmpty(txtName.Text)) sql += " AND Name LIKE '%' + #Name + '%'";
if (!string.IsNullOrEmpty(txtDesc.Text)) sql += " AND CONTAINS(DESCRIPTION, #description)";
But even so, this is still "safe" in the sql injection sense as long as you continue to use parameters for every part of the query that originates with user input.