使用日期访问数据库中的记录时出现问题。我做错了,这里不记得你是否需要#。我错过了什么?
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 + "";
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = Conn;
MyCommand.Connection.Open();
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (MyReader.Read())
{
TextBox1.Text = (string)MyReader["Note"];
}
答案 0 :(得分:3)
这里的简单改编是单引号:" ...Where Date = '07/04/2011'"
但正确的做法是使用参数:
MyCommand.CommandText =
"SELECT Id, Date, Note FROM NoteBook Where Date = @MarkDate";
MyCommand.Parameters.AddWithValue("@MarkDate", new DateTime(2011, 7, 4));
这也可以解决任何符号问题,你真的是指7月4日吗?
我通常会在笔记本条目中包含时间(而不是将该列称为日期) 如果是这样,您将需要BETWEEN条款或其他内容。