【问题标题】:I cannot get my computer's date, only its time我无法获取计算机的日期,只有时间
【发布时间】:2013-03-31 01:50:44
【问题描述】:

我希望我的 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 数据库结果。 (别管那些被用户错误包围的领主)。

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

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

【问题讨论】:

  • 无论如何我只是注意到我的 C# 应用程序中的代码 TimeString 和 DateString 有没有办法同时获得时间和日期字符串?

标签: c# mysql datetime


【解决方案1】:

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

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

代码sn-p,

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()
        }
    }
}

【讨论】:

  • 我不担心安全问题,因为我不会在线获取此应用程序,该应用程序只能由我信任的用户在我们的局域网中访问。我的意思是这是用于家庭共享和存储数据库。
  • 你的意思是我的MySql数据库中的类型,如果你的意思是我会尝试改变它。
  • 是的。为存储在数据库中的值使用适当的数据类型。
  • 另外,仅使用DateTime.Now
  • @Jayseer 就算只用在家里,除了SQL Injection,你也容易出现异常。如果我传递一个带有单引号的字符串(SQL 注入指示符),如Johnny's Place,它最终会破坏你的插入语句字符串。
猜你喜欢
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多