Using SQL Parameters for Insert statement.

Sometimes you need to insert a data to your database. Here is the safer way to insert a row using SQL parameter.
Passing parameters to SQL prevents you build dynamic SQL statement. Building a dynamic SQL statement is a security risk such as SQL injection.
Here is the sample code for insert statement using parameters.

public void InsertRowToDatabaseUsingParams()
 {
//create SQL connection.
using (SqlConnection conn = new SqlConnection(connectionString))
 {
//open sql connection.
conn.Open();
string sqlCommand = "Insert into TestTable (column1,column2) Values(@column1,@column2);";

using (SqlCommand cmd = new SqlCommand(sqlCommand, conn))
{
//add column value to parameters of SqlCommand
SqlParameter param = new SqlParameter("@column1", SqlDbType.VarChar, 50);
param.Value ="value1";
cmd.Parameters.Add(param);

param =new SqlParameter("@column2", SqlDbType.VarChar, 50);
param.Value ="value2";
cmd.Parameters.Add(param);

//Process
cmd.ExecuteNonQuery();

}
}
}

Kyoungsu Do
Software Developer
ImageSource, Inc.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s