I am working on a c# web application...I want to insert data from textbox to database ....I have written the query but it's not working:
string insertquery =
@"INSERT INTO [LocationInfo]([LocationIP], [LocationName])
VALUES ('" + TextBox2.Text + "','" + TextBox3.Text + "')
WHERE LocationID=null";
SqlCommand cmd = new SqlCommand(insertquery, sqlcon_QOEMetrices);
cmd.ExecuteNonQuery();
sqlcon_QOEMetrices
is my database connection object...
Please tell me if there is any syntax error or any statement missing.........
-
9hello sql injection!!Baz1nga– Baz1nga2012年03月31日 09:58:48 +00:00Commented Mar 31, 2012 at 9:58
-
5First problem: your code is vulnerable to SQL injection attacks. Don't include the values directly into your SQL. Use a parameterized SQL statement instead. Second problem: "it's not working" is a lousy description of what's happening. Tell us what's happening. If there's an exception, give us the full details. If it doesn't compile, give us the compile-time error. If it's inserting the wrong values, tell us about that.Jon Skeet– Jon Skeet2012年03月31日 09:58:51 +00:00Commented Mar 31, 2012 at 9:58
-
Remove "Where LocationID=null" from querycichy– cichy2012年03月31日 10:00:04 +00:00Commented Mar 31, 2012 at 10:00
-
use sqlparam to insert values into tables in order to survive sql injectiongout– gout2012年03月31日 10:00:39 +00:00Commented Mar 31, 2012 at 10:00
-
Also, "it's not working", is that the error you get?Mr Lister– Mr Lister2012年03月31日 10:04:06 +00:00Commented Mar 31, 2012 at 10:04
4 Answers 4
you can write query like following command
SqlCommand comm = new SqlCommand("INSERT INTO desg VALUES (@txtsno, @txtdesg, @txtbasic)", connection);
your_db.Open();
try {
comm.Parameters.AddWithValue("@txtsno", txtsno.Text.Trim());
comm.Parameters.AddWithValue("@txtdesg", txtdesg.Text.Trim());
comm.Parameters.AddWithValue("@txtbasic", txtbasic.Text.Trim());
comm.ExecuteNonQuery();
comm.Dispose();
comm = null;
}
catch(Exception ex)
{
throw new Exception(ex.ToString(), ex);
}
finally
{
your_db.Close();
}
1 Comment
You should NOT concatenate SQL query with direct values from forms.
Your ADO.NET code can look like this:
string query = "INSERT INTO [LocationInfo]([LocationIP], [LocationName])" +
"VALUES (@locIP, @locName)";
SqlCommand cmd = new SqlCommand(query, sqlcon_QOEMetrices);
cmd.Parameters.AddWithValue("@locIP", TextBox2.Text);
cmd.Parameters.AddWithValue("@locName", TextBox3.Text);
try
{
sqlcon_QOEMetrices.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
sqlcon_QOEMetrices.Close();
}
3 Comments
omit
WHERE LocationID=null
And prefer SQLCommand and Parameters. Not build strings with UI control values.
Comments
use LocationID IS NULL
instead of LocationID = NULL
and yes. your query is prone to SQL injection attacks as other people mentioned.