Optimal way to store datetime values in SQLite database (Delphi)

后端 未结 5 1275
无人及你
无人及你 2021-02-08 16:29

I will be storing datetime values in an SQLite database (using Delphi and the DISqlite library). The nature of the db is such that it will never need to be transferred between c

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-08 16:32

    I don't know if this answer is applicable to the DISqlite library but...
    Below is some code that illustrates what works for me using both Delphi 2010 and Tim Anderson's SQLite3 wrapper.

    SQL to create field:

      sSQL :=  'CREATE TABLE [someTable] (' +
                '  [somefield1] VARCHAR(12),' +
                '  [somefield2] VARCHAR(12),' +
                '  [myDateTime] DATETIME );';
    

    SQL to populate field:

     sSQL := 'INSERT INTO someTable(somefield1, somefield2, myDateTime)' + 
             '  VALUES ( "baloney1", "baloney2","' + FloatToStr(Now) + '");';
    

    Example of retrieving data from field:

    var
    sDBFilePathString: string;
    sl3tbl: TSqliteTable;
    fsldb : TSQLiteDatabase;
    FromdbDTField : TDateTime;
    
    begin
       ...
       ... 
        fsldb := TSQLiteDatabase.Create(sDBFilePathString); 
        sl3tbl := fsldb.GetTable('SELECT * FROM someTable');
        FromdbDateTime := StrToFloat(sl3tbl.FieldAsString(sl3tbl.FieldIndex['myDateTime']));
        Showmessage('DT: ' + DateTimeToStr(FromdbDTField));
    end;
    

    Result:

    **DT: 10/10/2013 1:09:53 AM**
    

    Like I mentioned on the first line - I don't know if this will work with the DISqlite library but if it does its a pretty clean way of handling things. I leave it to you to make things prettier or more elegant.

提交回复
热议问题