在 C# 中打开与 Mysql 的连接时,对象无法从 DBNull 转换为其他类型

问题描述 投票:0回答:1
Line 27: try
Line 28: {
Line 29:     Conn.Open();
Line 30:     MySqlReader = cmd.ExecuteReader();
Line 31:     if (MySqlReader.Read() == true)

我尝试更改 Mysql.dll,并添加对 Web 配置的引用,但它不起作用。我在打开连接时收到此错误:

'第29行:Conn.Open();'

mysql connection mysql-connector dbnull mysql-connect
1个回答
-1
投票

以下是排查和解决问题的一些步骤:

读取数据时检查DBNull

int value = MySqlReader.IsDBNull(columnIndex) ? defaultValue : MySqlReader.GetInt32(columnIndex);

try
{
    Conn.Open();
    MySqlReader = cmd.ExecuteReader();
    while (MySqlReader.Read())
    {
        // Example of reading an integer, with a check for DBNull
        int someColumnValue = MySqlReader.IsDBNull(columnIndex) ? 0 : MySqlReader.GetInt32(columnIndex);
        // Process other columns similarly
    }
}
catch (Exception ex)

{

// Log the exception details for debugging
Console.WriteLine(ex.Message);

}
finally
{
    // Close the reader and connection if open
    MySqlReader?.Close();
    Conn?.Close();

}
© www.soinside.com 2019 - 2024. All rights reserved.