【问题标题】:When retrieving MySQL date, it becomes date and time检索 MySQL 日期时,它变为日期和时间
【发布时间】:2020-03-20 07:20:33
【问题描述】:

我想问一下为什么当我从数据库中检索数据时,日期变成了日期和时间。

这是我的数据库:

这是我的 C# 代码:

private void runQuery()
{
    string query = txtQuery.Text;

    if(query == "")
    {
        MessageBox.Show("Empty Query");
        return;
    }

    string strSQLConnection = "datasource = 127.0.0.1;port = 3306; username = root; password =; database =inventory";
    MySqlConnection dbConnection = new MySqlConnection(strSQLConnection);
    MySqlCommand sqlCmd = new MySqlCommand(query, dbConnection);
    sqlCmd.CommandTimeout = 60;

    try
    {
        dbConnection.Open();

        MySqlDataReader myReader = sqlCmd.ExecuteReader();

        if(myReader.HasRows)
        {
            while(myReader.Read())
            {
                lstQuery.Items.Add(myReader.GetString(0) + " | " + myReader.GetString(1) +" | " + myReader.GetString(2));
            }
        }
        else
        {
            lstQuery.Items.Add("Query successfully executed!");
        }
    }
    catch(Exception e)
    {
        MessageBox.Show("Query error: " + e.Message);
    }
}

输出:

数据库:

【问题讨论】:

  • 我不确定我遗漏了哪些信息,请告诉我,我会添加它。谢谢。

标签: c# mysql xampp


【解决方案1】:

在 .NET 中,没有仅日期类型。处理日期值的类型称为DateTime,它代表日期和时间。因此,当您从数据库中检索日期值时,它会转换为 DateTime 值,时间部分为 00:00:00,然后通过 GetString() 方法转换为字符串。你应该做的是使用DateTime.ToString() 来格式化你喜欢的日期。

试试这样的:

string formattedDate = myReader.GetDateTime(2).ToString("yyyy-MM-dd");

参考资料:

【讨论】:

    猜你喜欢
    • 2013-08-20
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2020-06-02
    • 2021-08-19
    • 2013-06-16
    • 2019-04-25
    • 1970-01-01
    相关资源
    最近更新 更多