Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 适配器填充上的列名无效_C#_Sql - Fatal编程技术网

C# 适配器填充上的列名无效

C# 适配器填充上的列名无效,c#,sql,C#,Sql,当我从datetimePicker输入2016年6月19日时,我得到一个System.Data.SqlClient.SqlException,其中包含一个无效列名Jun on Fill函数的附加信息,这里是一个Jun是一个月,但它将其作为一个列 ReportForm.cs public void MakeDailyReport(string givenDate, DataGridView view) { con.Open(); cmd = new SqlCommand("SELE

当我从datetimePicker输入2016年6月19日时,我得到一个System.Data.SqlClient.SqlException,其中包含一个无效列名Jun on Fill函数的附加信息,这里是一个Jun是一个月,但它将其作为一个列

ReportForm.cs

public void MakeDailyReport(string givenDate, DataGridView view)
{
    con.Open();
    cmd = new SqlCommand("SELECT Date FROM FinalSales where Date = @datePicker", con);
    cmd.Parameters.AddWithValue("@datePicker", givenDate);
    cmd.ExecuteNonQuery();
    DateTime dateObject = (DateTime)cmd.ExecuteScalar();
    string dateObjectstring = Convert.ToString(dateObject.ToShortDateString());
    string givenDateString = Convert.ToString(givenDate);

    if (dateObjectstring == givenDateString)
    {
        DataTable dt = new DataTable();
        adapt = new SqlDataAdapter("SELECT Date FROM FinalSales where Date = " + givenDate + "", con);
        if (adapt != null)
        {
            adapt.Fill(dt);

            view.DataSource = dt;
        }
        else
        {
            MessageBox.Show("No Record found againts that date");
            con.Close();
        }
    }
    else
    {
        con.Close();
    }
}

不要使用字符串连接来生成查询,而是使用正确类型的sql参数。这也将防止sql注入和其他可能的问题(如本例)


请注意,我还使用了
dateTimePicker.Value.Date
来忽略时间部分。

givenDate的值是多少?在该上下文中,它似乎不是有效的SQL代码。通过将其视为参数值而不是可执行的SQL代码,您可能完全可以避免该问题。在第一个查询中,您使用了一个参数,而在第二个查询中,您使用了字符串串联。应为错误。为什么需要在此处进行查询
datefrom FinalSales where Date=“+givenDate+”
您正在从表中选择日期,您的条件是
Date=X;
输出也将与where中的相同condition@un-幸运的是:更好的是,没有人会对结果做任何事情(好吧,第一个)查询。然后出于某种原因,他继续将字符串转换为字符串。此代码有很多错误:-/感谢它的工作,但我没有得到任何输出SQL中的数据是“2016-06-19”,另一个日期是“2016年6月16日”“我怎么能定呢?”哈桑·索海尔:嗯,那是不同的日期。
=
运算符正在查找相同的值,而不是不同的值。根据描述,这里的类型也可能混在一起。如果您使用的是字符串而不是实际的日期和/或时间值,那么您有责任一致地格式化这些日期/时间字符串。这通常是你不想承担的责任。使用实际的
Date
值,而不是字符串。@David,你能在上面的解决方案中给我举个例子吗。@HassaanSohail:正如David所说,你的类型很混乱。当你想按日期时间过滤时,不要乱动字符串。也许您必须使用
dateTimePicker.Value.Date
来省略dateTimePicker.Value的时间部分。我已经相应地编辑了我的答案。
adapt = new SqlDataAdapter("SELECT [Date] FROM FinalSales where [Date] = @givenDate", con);
var dateParameter = adapt.SelectCommand.Parameters.Add("@givenDate", SqlDbType.DateTime);
dateParameter.Value = dateTimePicker.Value.Date;  // not string but the correct type DateTime