-2

In my database, I have a column that has a 'date' datatype.

That means It will only take dates in YYYY-MM-DD format.

My question is,

how do I send the current date from C# to the database?

Like, if I use CURDATE() in the query on PHPMyAdmin, it'd give me today's date in the format I want. But how can I somehow use that "CURDATE()" in C# Windows Form when I send information to the database?

                string query = "INSERT INTO player (date, name, level, experience) " +
                                 "VALUES ('" + DateTime.Today + "','" +
                                         getPlayerName(Tibia.Handle, (BattleList_Start + Base + (BattleList_Step * playerIndex) + 4)) + "'," +
                                         ReadInt32(LvlAdr + Base, 4, Tibia.Handle) + "," +
                                         ReadInt32(XpAdr + Base, 4, Tibia.Handle) + ")";
4

1 回答 1

13

好的,在我的数据库中,我有一列具有“日期”数据类型。这意味着它只会采用 YYYY-MM-DD 格式的日期。

不,它没有。这意味着这些值只是日期。数据库中的值是日期,而不是“特定格式的日期”。了解存储的数据和可用于显示或输入的文本表示之间的区别非常重要。

我的问题是,如何将当前日期从 C# 发送到数据库?

使用参数化 SQL,并将参数的值设置为DateTime.Today. 您根本不需要字符串表示。所以像:

// Work out the values beforehand
string name = getPlayerName(Tibia.Handle, 
                (BattleList_Start + Base + (BattleList_Step * playerIndex) + 4));
int level = ReadInt32(LvlAdr + Base, 4, Tibia.Handle);
int experience = ReadInt32(XpAdr + Base, 4, Tibia.Handle);

// Now do the database operations
string sql = @"INSERT INTO player (date, name, level, experience) 
               VALUES (@Date, @Name, @Level, @Experience)";
using (var conn = new MySqlConnection(...))
{
    conn.Open();
    using (var cmd = new MySqlCommand(sql, conn))
    {
        cmd.Parameters.Add("@Date", MySqlDbType.Date).Value = DateTime.Today;
        cmd.Parameters.Add("@Name", MySqlDbType.VarChar).Value = name;
        cmd.Parameters.Add("@Level", MySqlDbType.Int32).Value = level;
        cmd.Parameters.Add("@Experience", MySqlDbType.Int32).Value = experience;
        int rows = cmd.ExecuteNonQuery();
        // TODO: Validation of result (e.g. that 1 row was inserted)
    }
}

请注意,这将使用系统默认时区来计算您所说的“现在”是什么日期 - 如果您想要不同的时区,请提供更多信息。

或者,如果您使用 ORM(例如实体框架、NHibernate 等),通常这会被简化,您永远不需要直接指定 SQL - ORM 应该根据参数自动工作。

于 2013-07-02T18:42:42.027 回答