如何通过C#在SQLite数据库中写入变量DateTime值?
问题描述:
我对 C#
和 SQLite
数据库非常陌生,并且有一些变量与 TimeStamp
一起存储在 SQLite 数据库中.这是我的代码:
I'm very new to C#
and SQLite
database and have some variables which to be stored in SQLite database along with TimeStamp
.
Here is my code:
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
但它仍然不起作用.
But I'm getting error. I guess, SQLite doesn't support DateTime
. I tried converting DateTime now
to string
but it still doesn't work.
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 注入:
Use parameters to avoid SQL injection:
var sql = string.Format("insert into Table (Timestamp) values (@now)", now);
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("@now",now);