使用从下拉列表中选择的日期时间值,并在sql查询条件中使用它

本文关键字:并在 sql 查询 条件 日期 下拉列表 选择 时间 | 更新日期: 2023-09-27 17:49:30

我有一个下拉列表,我通过获取存储在我的数据库中的datetime值填充到AccessDataSource。因此,当我运行asp.net程序时,我得到以下示例:23-DEC-12 12:00:00 AM。这是我在AccessDataSource中使用的查询:

SELECT DISTINCT date_time FROM temperature

现在我要做的是在这个下拉列表中选择值(datetime值),并将其用作sql查询中的条件。这是我试图修复的代码:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    cnstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:''Users''user''Desktop''Thermal Analysis''thermal.accdb";
    OleDbConnection cn = new OleDbConnection(cnstr);
    cn.Open();
    OleDbCommand cmd = new OleDbCommand("SELECT ID,temp FROM temperature where date_time=#'" + DropDownList1.SelectedItem + "'# ", cn);
    OleDbDataReader dr = cmd.ExecuteReader();
}
谁能告诉我我做错了什么?

使用从下拉列表中选择的日期时间值,并在sql查询条件中使用它

使用

DropDownList1.SelectedValue

获取下拉列表的。该值是您希望在SQL语句中使用的值。此外,一定要考虑使用参数化查询,就像DJ Kraze在评论中提到的那样。

您已使用

 OleDbCommand cmd = 
      new OleDbCommand("SELECT ID,temp FROM temperature where date_time=#'" 
      + DropDownList1.SelectedItem + "'# ", cn);

是错误的。因为SelectedItemTextvalue的集合你应该使用文本或值

你的代码应该如下

OleDbCommand cmd = new OleDbCommand("SELECT ID,temp FROM temperature where date_time='" + DropDownList1.SelectedValue + "'", cn);

将您的OleDbcommand语句替换为:

OleDbCommand cmd = new OleDbCommand("SELECT ID,temp FROM temperature where date_time=#'" + DropDownList1.SelectedValue + "'# ", cn);