-3

Why am I getting this error, and how can I fix it?

ADO.NET code:

myConnection.Open();

string cmdStr = "SELECT COUNT(*) FROM Sale WHERE Date = '" + DateTime.Today + "' AND User = '" +     UserBox.Text + "'";

SqlCommand Pexist = new SqlCommand(cmdStr, myConnection3);

int P = Convert.ToInt32(Pexist.ExecuteScalar().ToString());

myConnection.Close();

Error:

Conversion failed when converting date and/or time from character string.

Zee-pro
  • 165
  • 1
  • 6
  • 13

3 Answers3

4

You get this error because you don't use parameters.

string cmdStr = "SELECT COUNT(*) FROM Sale WHERE Date = @dt " + 
                 "AND User = @usr " +     
                 "AND Item = @itm " + 
                 "AND Name = @name";

 SqlCommand Pexist = new SqlCommand(cmdStr, myConnection3);
 Pexist.Parameter.AddWithValue("@dt", DateTime.Today);
 Pexist.Parameter.AddWithValue("@usr", UserBox.Text);
 Pexist.Parameter.AddWithValue("@itm", ID505.Text);
 Pexist.Parameter.AddWithValue("@name", DropDownList1.SelectedItem.ToString());
 object result = Pexist.ExecuteScalar();
 int P = (result == null ? 0 : Convert.ToInt32(result));
 myConnection.Close();

When you use parameters, you let the database engine treat your input string. The database engine knows how to handle date, string and numbers. You are free from parsing problems and you avoid Sql Injection Attacks.

For example, what happen in your query string if the textbox ID505 contains a single quote?

Also, ExecuteScalar returns an object that is

The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty

So it is better to check for null before trying to convert the result in an integer.

EDIT Looking back at this question after a while I should add that in this particular case the return from ExecuteScalar could never be null. This is the case because the query uses the aggregate function COUNT(*) that will return always a valid number also in case of no record found.

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
0

Do use parameters. It is safer and will get you around conversion issues like this...

string cmdStr = " SELECT COUNT(*) FROM Sale WHERE Date = @d AND User = @u AND Item = @i AND Name = @n";
SqlCommand Pexist = new SqlCommand(cmdStr, myConnection3);
Pexist.Parameters.Add("d", SqlDataType.DateTime).Value = DateTime.Today;

and so on...

Rashack
  • 4,667
  • 2
  • 26
  • 35
-2

Replace the DateTime.Today with DateTime.Today.ToString("yyyy/MM/dd") should fix your problem.

Eric Fan
  • 147
  • 9