8

I have textBoxes in my application. The data entered in those textBoxes are to be inserted in the database. The commandString accepts string type only. 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 the cmdString with textBox.Text for each value or is there a better alternative available?

John Woo
  • 258,903
  • 69
  • 498
  • 492
Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97
  • It would kind of help, just a little, if you told us what programming language you're using. – ErikE Dec 22 '12 at 07:54

2 Answers2

28

use Command and Parameter to prevent from 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
        }
    }
}
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • i actually have little idea of databases but only the knowledge of c#. can you please tell me that the above code is enough to insert the data into database and will be available later, or some other statements need to be added? – Victor Mukherjee Dec 22 '12 at 09:28
  • 1
    see my updated answer, that snippet will insert a record in the database. – John Woo Dec 22 '12 at 09:32
1

You want to protect yourself from SQL Injection. Building up sql from strings is if not bad practice, at least very scary.

How To: Protect From SQL Injection in ASP.NET http://msdn.microsoft.com/en-us/library/ff648339.aspx

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

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