Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is a straight SQLITE question. I have the following basic table:
SQL
CREATE TABLE DateTest (
    id   INTEGER  PRIMARY KEY AUTOINCREMENT
                  UNIQUE
                  NOT NULL,
    Date DATETIME
);

I want to insert the date (10/31/2021) into the Date field as:
2021-10-31 00:00:00


Am I on the right track here, or am I just totally offbase?:

SQL
INSERT INTO DateTest VALUES (strftime('%Y/%m/%d', 2021/10/31));


Thanks for your help!

What I have tried:

Inordinate amount of time researching online, but knowledge is limited, I am just starting.
Posted
Updated 15-Feb-22 21:45pm

That is not OK, for several reasons:

1. a good INSERT statement lists the fields and the values; it may work without explicitly naming the fields but then any change to your table structure is bound to break your code.

2. Date literals (as well as datetime/timestamp/string literals) need quotes in SQL

3. IMO you don't need strftime; besides, this function has been DEPRECATED as of PHP 8.1.0
Just try ... VALUES ('2021/10/31')


Finally, the safe way to execute database operations is by using parameterized queries:
Parameters - Microsoft.Data.Sqlite | Microsoft Docs[^]

Please use them. Always. Advantages:
- no more quoting issues
- no more date formatting issues
- automatic protection against SQL Injection Attacks

By not using a parameterized query, you have to convert your date to a string, and then the database has to convert it back to a date. There is a double risk of errors about date formatting conventions, which gets totally avoided when the date is passed as a date, not as a string.

:)
 
Share this answer
 
v2
See Datatypes In SQLite[^] and Date And Time Functions[^] for details about how to store dates and times, and how to display them.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900