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?

1
  • It would kind of help, just a little, if you told us what programming language you're using. Commented Dec 22, 2012 at 7:54

2 Answers 2

29

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
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
see my updated answer, that snippet will insert a record in the database.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.