Insert new row into sql database table

I have text fields in my application. Data entered in these text fields must be inserted into the database. The commandString command only accepts a string type. So how can I implement the insert statement?

string cmdString="INSERT INTO books (name,author,price) VALUES (//what to put in here?)" 

Do I need to join cmdString with textBox.Text for each value, or is there a more efficient alternative?

+4
source share
2 answers

use Command and Parameter to prevent SQL Injection

 // other codes string cmdString="INSERT INTO books (name,author,price) VALUES (@val1, @va2, @val3)"; using (SqlCommand comm = new SqlCommand()) { comm.CommandString = cmdString; comm.Parameters.AddWithValue("@val1", txtbox1.Text); comm.Parameters.AddWithValue("@val2", txtbox2.Text); comm.Parameters.AddWithValue("@val3", txtbox3.Text); // other codes. } 

full code:

 string cmdString="INSERT INTO books (name,author,price) VALUES (@val1, @va2, @val3)"; string connString = "your connection string"; using (SqlConnection conn = new SqlConnection(connString)) { using (SqlCommand comm = new SqlCommand()) { comm.Connection = conn; comm.CommandString = cmdString; comm.Parameters.AddWithValue("@val1", txtbox1.Text); comm.Parameters.AddWithValue("@val2", txtbox2.Text); comm.Parameters.AddWithValue("@val3", txtbox3.Text); try { conn.Open(); comm.ExecuteNonQuery(); } Catch(SqlException e) { // do something with the exception // don't hide it } } } 
+19
source

You want to protect yourself from SQL Injection. Creating sql from strings is a good practice, at least very scary.

How to protect yourself from SQL injection in ASP.NET http://msdn.microsoft.com/en-us/library/ff648339.aspx

50 ways to enter your sql http://www.youtube.com/watch?v=5pSsLnNJIa4

Entity Framework http://msdn.microsoft.com/en-us/data/ef.aspx

+1
source

All Articles