Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting new row in sql database table

Tags:

c#

.net

sql

insert

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?

like image 845
Victor Mukherjee Avatar asked Dec 22 '12 07:12

Victor Mukherjee


2 Answers

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.
}
  • AddWithValue
  • Add (recommended method to use)

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
        }
    }
}
like image 78
John Woo Avatar answered Oct 26 '22 23:10

John Woo


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

like image 25
Michael Viktor Starberg Avatar answered Oct 26 '22 23:10

Michael Viktor Starberg