我正在尝试在我的项目中实现日期选择器功能,但我做不到这一点。我正在尝试在我的oracle字符串中传递日期选择器值,以便它将与我的db列进行比较,并在日期条件上返回结果...
每当我将它传递给select语句时,它都不会产生错误,特别是在点击按钮时它不会执行任何操作,除非它显示“未连接”。
str = "Select * from sania.doctor where APPOINTMENT_DATE = "+ datepicker1.value;
很明显这是合乎逻辑的错误但是我对这个C#概念不熟悉我需要有人告诉我如何传递它然后显示结果。
private void button1_Click(object sender, EventArgs e)
try
{
OracleCommand com;
OracleDataAdapter oda;
string ConString = "Data Source=XE;User Id=system;Password=sania;";
OracleConnection con = new OracleConnection(ConString);
{
// string id = dateTimePicker1.Text.Trim();
con.Open();
// str = "Select * from sania.doctor where APPOINTMENT_DATE = " + dateTimePicker1.value;
str = "select * from sania.doctor where APPOINTMENT_DATE to_date('"+dateTimePicker1.Value.ToString("yyyyMMdd") + "', 'yyyymmdd')";
com = new OracleCommand(str);
oda = new OracleDataAdapter(com.CommandText, con);
dt = new DataTable();
oda.Fill(dt);
Rowcount = dt.Rows.Count;
//int val = 0;
for (int i = 0; i < Rowcount; i++)
{
dt.Rows[i]["APPOINTMENT_DATE"].ToString();
//if (id == dateTimePicker1.Value)// this LINE SHOWS ERROR--because it is a string and I am using date with it. Don't know conversion
// {
// val = 1;
//}
}
// if (val == 0)
// { MessageBox.Show("INVALID ID"); }
// else
// {
DataSet ds = new DataSet();
oda.Fill(ds);
if (ds.Tables.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
else { MessageBox.Show("NO RECORDS FOUND"); }
}
}
//}
catch (Exception)
{ MessageBox.Show("not connected"); }
}
答案 0 :(得分:2)
不将值直接放入SQL ,而是使用bind 变量/参数 。对于Oracle:
// :prm_Appointment_Date bind variable declared within the query
String str =
@"select *
from sania.doctor
where Appointment_Date = :prm_Appointment_Date";
....
using(OracleCommand q = new OracleCommand(MyConnection)) {
q.CommandText = str;
// datepicker1.Value passed into :prm_Appointment_Date via parameter
q.Parameters.Add(":prm_Appointment_Date", datepicker1.Value);
...
}
这样做可以安全地从 SQL注入或格式/文化差异