On my SQL server I have a very simple table for testing, which only contains three rows:
ID
, Date
and Hours
.(varchar
,
You're preparing a perfect ground for SQL injections.
Also look here. There's an example of parametrized query.
The DateTime, which is represented by the string, isn't supported by the calender.
This error is being given because your C# application views the date 2012-14-10
as saying the 14th
month, 10th
day, and 2012th year
. The day and year work find, but the month doesn't. Further, don't try and change how your C# application views the date, that's based off the culture of the system.
You're confusing how to define a DateTime
object and how to display one.
Since you're storing your date as a DateTime
in SQL, there's not a good reason for me to believe that you would need to do any kind of parsing. Consider the below code sample.
var dataTable = new DataTable();
var dataAdapter = new SqlDataAdapter("SELECT * FROM YourTable", "{connection string}");
dataAdapter.Fill(dataTable);
var yourDate = dataTable.Rows[0]["Date"]; <=== the type will be DateTime, simple.
Let's take your example query:
"SELECT * FROM date_test WHERE id = '4' AND date BETWEEN '" + dt1 + "' AND '" + dt2 + "'";
And let's fix it a bit, consider the below example:
var dataTable = new DataTable();
var dataAdapter = new SqlDataAdapter("SELECT * FROM date_test WHERE id = @ID AND date BETWEEN @StartDate AND @EndDate", "{connection string}");
dataAdapter.SelectCommand.Parameters.AddWithValue("@ID", "4");
dataAdapter.SelectCommand.Parameters.AddWithValue("@StartDate", new DateTime(2012, 10, 1));
dataAdapter.SelectCommand.Parameters.AddWithValue("@EndDate", new DateTime(2012, 10, 14));
dataAdapter.Fill(dataTable);
var yourDate = dataTable.Rows[0]["Date"]; <=== the type will be DateTime, simple.