Saturday, 12 January 2013 13:56

use command parameters to pass values to SQL statements

Written by 
Rate this item
(0 votes)

command objects use parameters for passing values
to sql statements for type cheking,validation,guarding
against SQL injection attacks,etc.so its a good practice
to use command parameters to sql statements.

one can also pass values to sql procedures also.

a example demonstrates how to use command parameters-

SqlConnection conn = new SqlConnection(_connection.ConnectionString);
cmd = new SqlCommand("INSERT INTO Topics " +
" (UserId, Tid, Subject, Posted, Fid) " +
" Values(@UserId, @Tid, @Subject, @Posted)", conn);

cmd.Parameters.Add("UserId", SqlDbType.VarChar, 255).Value = UserId;
cmd.Parameters.Add("Tid", SqlDbType.Int).Value = CurTopicId + 1;
cmd.Parameters.Add("Subject", SqlDbType.VarChar, 255).Value = TopicSubjectText;
cmd.Parameters.Add("Posted", SqlDbType.DateTime).Value = System.DateTime.Now;

try
{
conn.Open();
cmd.ExecuteNonQuery();
}

Read 1229 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.
Login to post comments