Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the syntax to INSERT datetime variable INTO VALUES

Tags:

python

sql

What is the syntax for inserting a SQL datetime data type into a row? The following in Python gives a NULL value for the timestamp variable only.

timestamp = datetime.datetime.today()
print timestamp
query = "INSERT INTO table1 (name, class, time_update) VALUES('ONE','TWO',@timestamp)"
cursor.execute(query)
like image 523
Tom Avatar asked Apr 18 '26 05:04

Tom


2 Answers

I'm sure it depends on which database backend you're using, but in SQLite for example, you need to send your parameter as part of the query (that's what a parameterized statement is all about):

timestamp = datetime.datetime.today()
print timestamp
query = "INSERT INTO table1 (name, class, time_update) VALUES('ONE','TWO',?)"
cursor.execute(query, (timestamp,))
like image 165
voithos Avatar answered Apr 20 '26 22:04

voithos


It really depends on the database. For MySQL, according to this, you can specify a timestamp/datetime in several formats, mostly based on ISO8601: 'YYYY-MM-DD', 'YY-MM-DD', 'YYYYMMDD' and 'YYMMDD' (without delimiters) or if you want greater precision 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' ('YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS').

As far as querying goes you should probably parameterise (it's safer and a very good habit) by specifying a placeholder in the query string. For MySQL you could do:

query = "INSERT INTO table1 (name, class, time_update) VALUES('ONE','TWO',%s)"
cursor.execute(query, (timestamp,))

but the syntax for placeholders varies (depending on the db interface/driver) — see the documentation for your DB/Python interface.

like image 40
cosmix Avatar answered Apr 20 '26 23:04

cosmix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!