我对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();
我做错了吗?
答案 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);