.netsqlitedelphi-prismoxygene

How to insert and retrieve TIMESTAMP fields using SQL statement with SQLite?


I was able to insert TIMESTAMP as a string into my table, but when I read it out my program raises an error saying "String was not recognized as a valid DateTime."

Here is how I insert my values into the table.

sqlstr := 'INSERT INTO ALARMS (ALARMTIME) VALUES ("'+DateTime.Now.ToString+'");';
cnn := new SQLiteConnection('Data Source=AlarmLog.s3db');
cnn.Open;
var mycommand := new SQLiteCommand(cnn);
mycommand.CommandText := sqlstr;
var info := mycommand.ExecuteNonQuery;
cnn.Close;

Here is how I read it out.

    sqlstr := 'SELECT * from ALARMS';
    var dt := new DataTable;
    cnn := new SQLiteConnection('Data Source=AlarmLog.s3db');
    cnn.Open;
    var mycommand := new SQLiteCommand(cnn);
    mycommand.CommandText := sqlstr;
    var reader := mycommand.ExecuteReader;
    dt.Load(reader); <---------------------Here is where I am getting the error, "String was not recognized as a valid DateTime."
    reader.Close;
    cnn.Close;

I know why I am getting the error, but why can't I insert the TIMESTAMP as a date and time instead of string or text type. If you notice in my SQL query, I have quotation marks around the DateTime.Now.ToString statement. That's the only way it accepts my SQL Statement.


Solution

  • Pass a date format that SQLite recognizes, like:

    DateTime.Now.ToString("yyyy-MM-ddTHH:mm")
    

    Other valid formats on this SQLite manual page.

    Even better is to use a parameter, like:

    sqlstr := 'INSERT INTO ALARMS (ALARMTIME) VALUES ($dt);';
    ...
    mycommand.Parameters.AddWithValue("$dt", DateTime.Now);