将 C# 中的 MySqlDateTime 值插入 MySQL 数据库

Inserting a MySqlDateTime value from C# to a MySQL database

我有一个 C# 应用程序需要将当前日期时间插入 MySQL 数据库中的 datetime 字段。我该如何实现?

我正在使用 MySQL Connector/NET 6.9.9。以下是我到目前为止所尝试过的。 data.currentDateTime 属于 MySqlDateTime.

类型

数据库中的预期结果是正确的日期时间,但实际值是 0000-00-00 00:00:00

    // Set up data object and add datetime

    MyData data = new MyData();
    data.currentDateTime = new MySqlDateTime(DateTime.Now);

    // Insert into database
    try
    {
        MySqlConnection conn = getMySqlConnection();
        conn.Open();

        MySqlCommand cmd = new MySqlCommand(@"
            INSERT INTO my_data (`current_datetime`)
            VALUES (@currentDateTime)
        ", conn);

        log.Debug(data.currentDateTime); // correct timestamp

        cmd.Parameters.AddWithValue("currentDateTime", data.currentDateTime);
        cmd.ExecuteNonQuery();

       // Value in the database is 0000-00-00 00:00:00

    } catch (Exception e) {
        // Hnadle exception
    }

我的数据class:

    public class MyData
    {
        public int id { get; set; }
        public MySqlDateTime currentDateTime { get; set; }
        // Other fields

        public MyData()
        {
            // Empty constructor
        }
    }

您遇到了 MySQL bug 91199 的变体。

使用默认值 SQL mode,MySQL 服务器将拒绝由 Connector/NET 序列化的不正确 MySqlDateTime,并出现 Incorrect datetime value 错误。

但是,如果您的 MySQL 服务器未启用 NO_ZERO_DATE and strict mode,则尝试插入 MySqlDateTime 会“成功”,但插入的值将是 0000-00-00 00:00:00.

bug 91119 has been incorrectly closed as a duplicate, this probably isn't likely to be fixed soon. As a workaround, you could consider switching to MySqlConnector 以来,Connector/NET 的 OSS 替代方案修复了此问题(以及许多其他错误)。

要使用 MySql.Data 解决此问题,请添加基础 DateTime 作为参数值,而不是 MySqlDateTime 对象:

cmd.Parameters.AddWithValue("currentDateTime", data.currentDateTime.GetDateTime());

请注意,如果 MySqlDateTime 无法转换为 DateTime,这将抛出 MySqlConversionException;如果这可能发生在您的代码中,您需要测试 data.currentDateTime.IsValidDateTime 并在 false.

时执行其他操作