我希望我的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有没有办法让它们像时间和日期字符串一样?
答案 0 :(得分: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()
}
}
}