[ACCEPTED]-C# - SQLClient - Simplest INSERT-tsql

Accepted answer
Score: 18
using (var conn = new SqlConnection(yourConnectionString))
{
    var cmd = new SqlCommand("insert into Foo values (@bar)", conn);
    cmd.Parameters.AddWithValue("@bar", 17);
    conn.Open();
    cmd.ExecuteNonQuery();
}

0

Score: 2

Since you seem to be just getting started 8 with this now is the best time to familiarize 7 yourself with the concept of a Data Access 6 Layer (obligatory wikipedia link). It will be very helpful for you 5 down the road when you're apps have more 4 interaction with the database throughout 3 and you want to minimize code duplication. Also 2 makes for more consistent behavior, making 1 testing and tons of other things easier.

Score: 0
using (SqlConnection myConnection new SqlConnection("Your connection string")) 
{ 
    SqlCommand myCommand = new SqlCommand("INSERT INTO ... VALUES ...", myConnection); 
    myConnection.Open(); 
    myCommand.ExecuteNonQuery(); 
}

0

More Related questions