Brian Warshaw
Brian Warshaw

Reputation: 22974

C# - SQLClient - Simplest INSERT

I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace.

I'm using SqlConnection for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.

Upvotes: 10

Views: 18767

Answers (3)

AlexCuse
AlexCuse

Reputation: 18306

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

Upvotes: 2

aku
aku

Reputation: 123994

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

Upvotes: 1

Matt Hamilton
Matt Hamilton

Reputation: 204209

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();
}

Upvotes: 20

Related Questions