如何通过C#在SQLite数据库中写入变量DateTime值? [英] How to write variable DateTime value in SQLite database through C#?
本文介绍了如何通过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);
这篇关于如何通过C#在SQLite数据库中写入变量DateTime值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文