我对 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();
我做错了什么吗?
最佳答案
使用参数避免SQL注入(inject):
var sql = string.Format("insert into Table (Timestamp) values (@now)", now);
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("@now",now);
关于c# - 如何通过C#在SQLite数据库中写入变量DateTime值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42512782/