when i compile the following code , “Conversion failed when converting datetime from character string” exception raises , what is wrong with that ?
code :
DateTime after3Dyas = DateTime.Now.AddDays(3);
try
{
Con.Open();
SqlCommand Command = Con.CreateCommand();
Command.CommandText = "Select * from Forcast Where City='" + city + "' And Date between '" + DateTime.Now.Date + "' and '" + after3Dyas.Date + "'";
SqlDataReader thisReader = Command.ExecuteReader();
int i=0;
while (thisReader.Read())
{
//do something
i++;
}
thisReader.Close();
The database is trying to convert the value from whatever
DateTime.ToStringis giving you… do you really want to trust that .NET on your calling machine and SQL Server use exactly the same format? That sounds brittle to me.Avoid this by not putting the value into the SQL directly in the first place – use a parameterized query. This not only avoids conversion issues, but also (equally importantly) avoids SQL injection attacks.
Sample code: