[英]query string data type mismatch
我正在使用OLEDB使用日期时间选择器查询Excel文件,但是在Cireria表达式错误中,我一直遇到数据类型不匹配的情况。
Excel中日期的格式为“ 6/08/2012 10:00”
DateTime time = dateTimePicker1.Value;
MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time + "')", MyConnection);
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
bindingSource1 = new BindingSource();
bindingSource1.DataSource = DtSet;
bindingSource1.DataMember = DtSet.Tables[0].TableName;
dataGridView1.DataSource = bindingSource1;
MyConnection.Close();
您将时间作为字符串传递给查询,因此您可以使用 ToString()使其起作用:
MyCommand = new OleDbDataAdapter("select * from [CR$] where ([Req Start Date] >='" + time.ToString("%M/dd/yyyy HH:mm") + "')", MyConnection);
但是您确实应该将其设为参数。 另外,这样更安全。
using (OleDbConnection connection = new OleDbConnection(yourConnectionString))
{
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [CR$] where [Req Start Date] >= ?", connection);
adapter.SelectCommand.Parameters.Add("@p1", OleDbType.Date);
adapter.SelectCommand.Parameters["@p1"].Value = time;
try
{
connection.Open();
adapter.Fill(DtSet);
}
catch (Exception ex)
{
//handle error
}
}
了解更多信息: OleDbParameter类
创建一个OleDbCommand并将值作为参数传递。 然后使用Command作为OleDbAdapter构造函数的参数...
string queryString = "select * from [CR$] where ([Req Start Date] >= ?)";
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Parameters.Add("@p1", OleDbType.DateTime).Value = time;
MyCommand = new OleDbDataAdapter(queryString, MyConnection);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.