我正在编写一个代码,我需要从列表框中选择,并从2 datepicker中选择以显示在datagridview上。
我的第一个代码版本已经只使用了日期范围,但是当我已经包含了列表框时,我开始收到错误。
这是我的疑问:
private void button6_Click(object sender, EventArgs e)
{
OleDbDataAdapter ad = new OleDbDataAdapter("select * from customer where network_name=" + listBox1.SelectedItem.ToString() +" where date_loaded between #" + dateTimePicker1.Value.ToShortDateString() + "# and #" + dateTimePicker2.Value.ToShortDateString() + "#", mycon);
DataSet ds = new DataSet();
ad.Fill(ds, "load");
dataTable = ds.Tables["load"];
if (ds.Tables[0].Rows.Count > 0)
{
dataGridView1.DataSource = ds;
dataGridView1.DataMember = ds.Tables[0].ToString();
}
}
答案 0 :(得分:4)
网络名称是一个文本值,因此需要用单引号括起来。另外,您有两个 WHERE 子句。用 AND 子句替换第二个,并将其包装在一组括号中。试试这个:
OleDbDataAdapter ad = new OleDbDataAdapter("select * from customer where network_name='" + listBox1.SelectedItem.ToString() +"' AND (date_loaded between #" + dateTimePicker1.Value.ToShortDateString() + "# and #" + dateTimePicker2.Value.ToShortDateString() + "#)", mycon);
答案 1 :(得分:1)
请参考化您的查询。准备好的语句可以防止SQL注入攻击,并且性能更好。请参阅:Give me parameterized SQL, or give me death。
我自己并不太熟悉OleDb(更像是一个MySQL人),但它应该是这样的。
cmd.Connection = mycon;
cmd.CommandText = "SELECT * FROM customer WHERE " +
"network_name = ? AND (date_loaded BETWEEN #?# and #?#)"
cmd.Parameters.Add("@network_name", OleDbType.VarChar);
cmd.Parameters.Add("@D1", OleDbType.DBDate);
cmd.Parameters.Add("@D2", OleDbType.DBDate);
cmd.Parameters["@network_name"].Value = listBox1.SelectedItem.ToString();
cmd.Parameters["@D1"].Value = dateTimePicker1.Value.ToShortDateString();
cmd.Parameters["@D2"].Value = dateTimePicker2.Value.ToShortDateString();
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
答案 2 :(得分:-1)
在查询中有两个位置,用和替换第二个。
select * from customer where network_name=" + listBox1.SelectedItem.ToString() +" and date_loaded between #" + dateTimePicker1.Value.ToShortDateString() + "# and #" + dateTimePicker2.Value.ToShortDateString() + "#"