Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to insert python datetime into SQL DATE

Trying to insert python datetime into SQL DATE but an error keeps appearing saying OperationalError: near "02": syntax error

import  sqlite3
conn=sqlite3.connect("Date_time3.db")
print("Database Opened successfully")
conn.execute("""
CREATE TABLE ADMIN(
EXPIRE DATETIME PRIMARY KEY
)
""")

This is my database^

import datetime 
import pytz
import  sqlite3

today = datetime.datetime.now()
date_time = today.strftime("%m/%d/%Y, %H:%M:%S")

conn=sqlite3.connect("Date_time3.db")
print("Database Opened successfully")

conn.execute("INSERT INTO ADMIN(EXPIRE) VALUES " +date_time);



conn.commit()
print ("Records inserted successfully")
conn.close()
"""
###Output###
#Database Opened successfully
#Records inserted successfully
#"""
print ("Table ADMIN created successfully")
"""
####Output###
Database Opened successfully
Table ADMIN created successfully
"""

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Change this:

conn.execute("INSERT INTO ADMIN(EXPIRE) VALUES " +date_time);

to

conn.execute('INSERT INTO ADMIN(EXPIRE) VALUES (?)', [date_time]);

As you are running SQL commands, they work differently from Python. So you cannot use + operators. You need to use placeholders like (?)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading