如何通过C#在SQLite数据库中编写变量DateTime值?

时间:2017-02-28 15:31:17

标签: c# sqlite datetime

我对C#SQLite数据库很新,并且有一些变量可以与TimeStamp一起存储在SQLite数据库中。 这是我的代码:

    DateTime now = DateTime.Now;
    m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
    m_dbConnection.Open();
    var sql = string.Format("insert into Table (Timestamp) values ({0})", now);
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    command.ExecuteNonQuery();

但我收到错误。我猜,SQLite不支持DateTime。我尝试将DateTime now转换为string,但它仍然无效。

    DateTime now1 = DateTime.Now;
    var now = now1.ToString("hh.mm.ss.fff");
    m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
    m_dbConnection.Open();
    var sql = string.Format("insert into Table (Timestamp) values ({0})", now);
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    command.ExecuteNonQuery();

我做错了吗?

1 个答案:

答案 0 :(得分:2)

使用参数来避免SQL注入:

var sql = string.Format("insert into Table (Timestamp) values (@now)", now);
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("@now",now);