简体   繁体   中英

System.InvalidCastException: 'Specified cast is not valid.' C# MYSQL

I am trying to use this code to get the sum of amount from database:

MySqlCommand cmdsumpayment = new MySqlCommand("SELECT sum(amount) as'total' from payments where unit_id = " + UNITID + " AND deleted_at IS NULL", conn);
                        MySqlDataReader rdr2 = cmdsumpayment.ExecuteReader();
                        if (rdr2.HasRows) {
                            while (rdr2.Read())
                        {
                            TOTALPAYMENTS = rdr2.GetInt32("total");
                        }
                        }
                        else
                            MessageBox.Show("nothing found");

It works and I can get the sum(amount) from the payments table but my problem is if I search for something that does not have payments, I get this error:

System.InvalidCastException: 'Specified cast is not valid.

For example, if unit id = 1 and it does have payments, I can have the result in TOTALPAYMENTS but if it does not have any payments I get errors and the application crashed. can someone help me with how to handle the empty search without crashing? I also try if (rdr2.HasRows) but it does not work, I don't know why.

I am 100% sure that you have amount null in the table and then you are getting type cast while converting to integer. With the code you have posted you'll not get the type cast exception if there are no rows in the table for the given condition. So you can put breakpoint and debug or put some logs. You can also try running the query directly into the database to see whether it's returning records or not.

You can modify the query if amount is null.

SELECT sum(isnull(amount, 0)) as'total' from payments where unit_id = " + UNITID + " AND deleted_at IS NULL

And I would recommend to use parameterised query to avoid sql injection.

Edit : I have got the root cause of your issue. SqlDataReader.GetInt32 expects integer value and you are passing string value. So you need to pass 0 instead of “total” . As mentioned in the documentation you should call IsDBNull to check for null values before calling this method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM