C# 错误:需要一个或多个参数

C# 错误:需要一个或多个参数,c#,oledb,C#,Oledb,这是C代码,给了我一个错误,access数据库中需要一个或多个参数,有人能帮我吗?…我被挂了,因为这个错误 代码如下: string date = textBox1.Text; con = new OleDbConnection(cs); con.Open(); String sql = "SELECT * From Sales where InvoiceDate = date "; cmd = new OleDbCommand(sql, con); cmd.Execut

这是C代码,给了我一个错误,access数据库中需要一个或多个参数,有人能帮我吗?…我被挂了,因为这个错误

代码如下:

string date = textBox1.Text; 
con = new OleDbConnection(cs); 
con.Open();        
String sql = "SELECT * From Sales where InvoiceDate = date "; 
cmd = new OleDbCommand(sql, con); 
cmd.ExecuteNonQuery(); 
DataTable dt = new DataTable(); 
dt.Load(cmd.ExecuteReader()); 
dataGridView1.DataSource = dt; 
第一个缺陷:您没有提到cs-isi的意思,只是向我们展示了连接字符串,但这不是什么大问题,因为它没有抛出错误

第二个缺陷:InvoiceDate=date,此处date既不是值也不是变量

将其用作变量

将其用作直接值

第三个缺陷:cmd.ExecuteNonQuery,这是不必要的

第四个缺陷:我不应该称之为缺陷,而是一种知识共享:您可以创建一个单独的DataAdapter,然后使用它填充表:

 OleDbDataAdapter ada = new OleDbDataAdapter(cmd);
 ada.Fill(mydatatable);
最大的漏洞:Sql注入,请不要让攻击者轻易攻击。而是使用参数:


首先,我建议将该日期解析为DateTime,因为我希望您的InvoiceDate是DB中的实际日期类型。其次,您需要使用参数来传递值。最后删除该ExecuteOnQuery。您还应该将一次性物品放入using语句中,以便正确关闭连接

DateTime date;
if(!DateTime.TryParse(textBox1.Text, out date))
{
    //Do whatever you need to indicate a bad date.
}

using(var con = new OleDbConnection(cs))
{
    con.Open();        
    String sql = "SELECT * From Sales where InvoiceDate = @date"; 
    using(var cmd = new OleDbCommand(sql, con))
    {
        cmd.Parameters.Add("@date", /*Insert correct type here*/).Value = date;
        DataTable dt = new DataTable(); 
        dt.Load(cmd.ExecuteReader()); 
        dataGridView1.DataSource = dt; 
    }
}

字符串日期=textBox1.Text;con=新的OLEDB连接;不公开;字符串sql=从销售中选择*,其中InvoiceDate=日期;cmd=新的OleDbCommandsql,con;cmd.ExecuteNonQuery;DataTable dt=新的DataTable;dt.Loadcmd.ExecuteReader;dataGridView1.DataSource=dt`请改进你的问题。另外,请研究和,以查看发布到此网站的问题中的预期内容。字符串sql=SELECT*From Sales,其中InvoiceDate=date;字符串中的日期部分与日期变量无关。您需要添加一个参数。您需要研究如何使用参数。其中InvoiceDate=date不会神奇地传递日期变量的值为什么在正确调用ExecuteReader后调用ExecuteOnQuery?人们希望名为InvoiceDate的列不会存储为varchar@juharr,我希望我的回答能很好地描述OP的问题,并给他一些提示。关于日期和时间,我添加了一个附加注释来通知OP,他可以根据需要更改数据类型,如果他理解这一点,他肯定可以进行DateTime解析/转换:。。。希望你明白:OP是不是很活跃??现在为发布一个巨大的答案感到难过:
 OleDbDataAdapter ada = new OleDbDataAdapter(cmd);
 ada.Fill(mydatatable);
 "SELECT * From Sales where InvoiceDate=@date"
 cmd.Parameters.Add("@date", OleDbType.Varchar).Vale = dateStringHere ///change data-type from varchar as required
DateTime date;
if(!DateTime.TryParse(textBox1.Text, out date))
{
    //Do whatever you need to indicate a bad date.
}

using(var con = new OleDbConnection(cs))
{
    con.Open();        
    String sql = "SELECT * From Sales where InvoiceDate = @date"; 
    using(var cmd = new OleDbCommand(sql, con))
    {
        cmd.Parameters.Add("@date", /*Insert correct type here*/).Value = date;
        DataTable dt = new DataTable(); 
        dt.Load(cmd.ExecuteReader()); 
        dataGridView1.DataSource = dt; 
    }
}