0

我希望我的 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)。

在此处输入图像描述

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

在此处输入图像描述

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

4

1 回答 1

5

首先,不要将日期作为字符串存储在数据库中。为它使用正确的数据类型,DATE或者DATETIME.

其次,你的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()
        }
    }
}
于 2013-03-31T01:55:07.473 回答