对象不能从DBNull转换为其他类型? C#

时间:2017-07-27 03:16:46

标签: c# mysql

我有一个数据库查询,当我在MySql中运行查询时,它返回值。但是当我在代码中运行它时,我得到的对象无法从DBNull转换为其他类型的异常。如何从代码中检索数据?

public int getLatestReading(string connstr, string gId, string mId, DateTime date)
    {

        int active = 0;
        MySqlConnection myconn = new MySqlConnection(connstr);
        String sqlstr = "Select max(ar.ActualReading) From actualmeterreading ar Inner Join meterreadingrecords mr On mr.ActualMeterReadingID = ar.ID Inner join machinemeterreadinglist mml on mml.ID = ar.MachineMeterReadingId Inner join grouping g on g.ID = mml.Grouping inner join machines m on m.ID = mml.MachineID where g.ID = '" + gId + "' and m.ID = '" + mId + "' and mr.rDate > '" + date + "'";
        MySqlCommand cmd = new MySqlCommand(sqlstr, myconn);
        myconn.Open();
        active = Convert.ToInt32(cmd.ExecuteScalar());
        myconn.Close();
        myconn.Dispose();
        return active;
    }

2 个答案:

答案 0 :(得分:3)

使用以下代码:

public int getLatestReading(string connstr, string gId, string mId, DateTime date)
    {

        int active = 0;
        MySqlConnection myconn = new MySqlConnection(connstr);
        String sqlstr = "Select max(ar.ActualReading) From actualmeterreading ar Inner Join meterreadingrecords mr On mr.ActualMeterReadingID = ar.ID Inner join machinemeterreadinglist mml on mml.ID = ar.MachineMeterReadingId Inner join grouping g on g.ID = mml.Grouping inner join machines m on m.ID = mml.MachineID where g.ID = '" + gId + "' and m.ID = '" + mId + "' and mr.rDate > '" + date + "'";
        MySqlCommand cmd = new MySqlCommand(sqlstr, myconn);
        myconn.Open();
        active = !Convert.IsDBNull(cmd.ExecuteScalar())?Convert.ToInt32(cmd.ExecuteScalar()):0;
        myconn.Close();
        myconn.Dispose();
        return active;
    }

答案 1 :(得分:0)

解决此问题的一种方法是确保查询永远不会返回null。您可以使用MySql ifnull函数执行此操作,方法是更改​​您的查询:

Select ifnull(max(ar.ActualReading), 0) ...