指定的强制转换是无效的SQLite空SELECT值

时间:2016-08-17 15:42:39

标签: c# sql winforms

我试图将@WE的日期与@to和@to之间的日期相加,如下所示

DateTime from = DateTime.Parse(dt_From.Value.ToShortDateString());
DateTime to = DateTime.Parse(dt_To.Value.ToShortDateString());
SQLiteConnection con = new SQLiteConnection(Properties.Settings.Default.ConnectionString);
SQLiteCommand cmd = null;
con.Open();

//Total Items Sold
string query = " SELECT SUM(total) FROM acc_items_income WHERE date BETWEEN @from AND @to AND deleted = 0 ";
cmd = new SQLiteCommand(query, con);
cmd.Parameters.Add(new SQLiteParameter("@from", from));
cmd.Parameters.Add(new SQLiteParameter("@to", to));

我试图阅读它,如图所示

SQLiteDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    double soldItems = dr.GetDouble(0);
    txtTotalSoldItems.Text = soldItems.ToString("c", naira);
}

我现在的错误是,当我从日期时间不在数据库中的行中选择,或者无法对没有值的列进行SUM时,我就会收到此错误。

指定的演员表无效

1 个答案:

答案 0 :(得分:0)

在尝试读取列之前,需要检查DBNull值。

while (dr.Read()) 
{
    if (dr.IsDBNull(0)) { //Check for a null value at the 0 index
        soldItems = 0;
    } else { 
        soldItems = dr.GetDouble(0);
    }
}