Keshav
Keshav

Reputation: 103

How to write variable DateTime value in SQLite database through C#?

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();

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();

Am I doing something wrong?

Upvotes: 3

Views: 1801

Answers (1)

apomene
apomene

Reputation: 14389

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);

Upvotes: 3

Related Questions