我无法得到我的电脑的日期,只有它的时间

时间:2013-03-31 01:50:44

标签: c# mysql datetime

我希望我的C#应用​​程序能够获取计算机的时间和日期,但它只获得时间而不是日期,所以这里是代码。

ApareceCrudLib b = new ApareceCrudLib("localhost", "root", "", "cashieringdb");
string theDate = DateTime.Now.ToShortTimeString();
string query = "INSERT INTO sales (price, user, date) " +
    "VALUES(" +
    "'" + txtQuant.Text + "'," +
    "'" + txtLog.Text +"'," +
    "'" + theDate +"')";
b.mysqlInsert(query);

这是我的MySql数据库结果。 (别担心用户错误地包围的lordens)。

enter image description here

这是我的日期结构设置为Varchar,长度/值设置为10.

enter image description here

无论如何,我只是注意到我的C#应用​​程序中的代码TimeString和DateString有没有办法让它们像时间和日期字符串一样?

1 个答案:

答案 0 :(得分:5)

首先,不要将日期作为字符串存储在数据库中。为其使用正确的数据类型DATEDATETIME

其次,你INSERT陈述很弱。 SQL Injection容易受到攻击。 必须值必须参数化。

代码段,

string connStr = "connection string here";
string insertStr = @"INSERT INTO sales (price, user, date)
                        VALUES (@price, @user, @date)";
using (MySqlConnection conn = new MySqlConnection(connStr))
{
    using (MySqlCommand comm = new MySqlCommand())
    {
        comm.Connection = conn;
        comm.CommandType = CommandType.text;
        comm.CommandText = insertStr;
        comm.Parameters.AddWithValue("@price", txtQuant.Text);
        comm.Parameters.AddWithValue("@user", txtLog.Text);
        comm.Parameters.AddWithValue("@date", DateTime.Now);
        try
        {
            conn.Open();
            comm.ExecuteNonQuery();
        }
        catch(MySqlException ex)
        {
            // don't hide the exception
            // do something
            // ex.ToString()
        }
    }
}