Hi, i have code right now with string concatenation like :
sSQL = "select * from table where a=b";
if (current.Request["ct"] != null && current.Request[ct] != "")
{
sSQL += " AND ct = '" + current.Request[ct] + "' ";
}
if (current.Request["dt"] != null && current.Request[dt] != "")
{
sSQL += " AND dt = '" + current.Request[dt] + "' ";
}
and few more (if statements) like these.......
Now i want to use sqlparameters instead for efficiency.
Problem is how can i do that? Do i have to write those if's to concatenate sSQL and then assign it to command object and then write if's again for adding parameters? i am sure there is an efficient way to do this.
thanks
-Samir
Jan MontanoPosted Jun 19, 2008, 10:02 PM
Please see code below.
If you'll notice, I added a parameter even before initializing the command text. Validation of command text and parameters will only happen during ExecuteReader(). Same principle applies with your issue. You can add as many parameters as you would like even with the wrong commandtext and your application wouldn't even complain, until you execute ExecuteReader().
static void Test1()
{
SqlConnection sqlConnection = new SqlConnection("Data Source=ce00959dc;Initial Catalog=northwind;User Id=samir;Password=samir;");
SqlCommand sqlCommand = new SqlCommand();
SqlDataReader sqlDataReader = null;
System.Data.SqlClient.SqlParameter sqlParameter = sqlCommand.CreateParameter();
sqlParameter.ParameterName = "CategoryName";
sqlParameter.Value = "Beverages";
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = System.Data.CommandType.Text;
sqlCommand.Parameters.Add(sqlParameter);
sqlCommand.CommandText = "SELECT * FROM Categories WHERE CategoryName=@CategoryName";
sqlConnection.Open();
sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
Console.WriteLine("Category = " + (string)sqlDataReader["CategoryName"]);
}
sqlConnection.Close();
}
samir samirPosted Jun 19, 2008, 10:46 AM
Jan MontanoPosted Jun 18, 2008, 10:24 PM
Please see this link for info on how to use sqlparameters ->
Lesson 06: Adding Parameters to Commands
Goodluck.