Friday, February 24, 2012

C# Parameterized Query with null values

Hello.
I have (2) related questions.
#1: I am using a paramterized query, but am unable to make it work if one of the values happens to be null.
if (Request.Form["txtLink1"] != "")
{
mySqlCmd.Parameters.Add(new SqlParameter("@.link1",SqlDbType.VarChar));
mySqlCmd.Parameters["@.link1"].Value =Request.Form["txtLink1"];
}
else
{
mySqlCmd.Parameters.Add(new SqlParameter("@.link1",SqlDbType.VarChar));
mySqlCmd.Parameters["@.link1"].Value = null;
}
If txtLink1 happens to be empty, I want @.link1 to enter null. Thecolumn in the Sql Server allows for nulls, but I get an error messagethat says no value was supplied. In short, how do I supply a null valueusing a parameterized query?
#2: For debugging purposes, how can I view what my SQL string lookslike (with all the values entered) before it gets submitted to thedatabase? When I view the string, it still contains the placeholdervalues (@.link1) instead of the actual values.
Thanks in advance!
-Brenden
(1) You dont have to be redundant in declaring the variable twice. You could move the line

mySqlCmd.Parameters.Add(new SqlParameter("@.link1", SqlDbType.VarChar));

out of your IF loop. as in :

mySqlCmd.Parameters.Add(new SqlParameter("@.link1", SqlDbType.VarChar));
if (Request.Form["txtLink1"] != "")
{
mySqlCmd.Parameters["@.link1"].Value = Request.Form["txtLink1"];
}
else
{
mySqlCmd.Parameters["@.link1"].Value =Dbnull.Value;
}
(2) and use DbNull.Value for nulls.
(3) You might also want to add in the size of the parameter to avoid issues later.
mySqlCmd.Parameters.Add(new SqlParameter("@.link1", SqlDbType.VarChar,100));|||ThanksDinakar!
That solved my issue.
Much appreciated.

No comments:

Post a Comment