Accessing record using a Date
Having a problems accessing a record in a database using date. I'm doing something wrong here cannot remember if you need to have #. What am I missing?
SqlDataReader MyReader;
SqlConnection Conn;
Conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NoteBook.mdf;Integrated Security=True;User Instance=True");
SqlCommand MyCommand = new SqlCommand();
MyCommand.CommandText = "SELECT Id, Date, Note FROM NoteBook Where Date = #07/04/2011#";//Id = 1"; //; // + Message.Text + "";
MyCom开发者_如何学编程mand.CommandType = CommandType.Text;
MyCommand.Connection = Conn;
MyCommand.Connection.Open();
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (MyReader.Read())
{
TextBox1.Text = (string)MyReader["Note"];
}
The simple adaptation here is single quotes: " ...Where Date = '07/04/2011'"
But the correct thing to do is use a parameter:
MyCommand.CommandText =
"SELECT Id, Date, Note FROM NoteBook Where Date = @MarkDate";
MyCommand.Parameters.AddWithValue("@MarkDate", new DateTime(2011, 7, 4));
That would also solve any notational issues, did you really mean the 4th of July ?
And I would usually include the Time in a Notebook entry (and not call that column Date).
If so, you will need a BETWEEN clause or something.
精彩评论