Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite3 with Python - Query from external file

I would like to create my DB by an external file like:

database = "../data/cm4payroll.db"
query = "../data/emdb.sql"
# Datenbankverbindung herstellen
self.connection = sqlite3.connect(self.database)
self.cursor = self.connection.cursor()
# Datenbank erstellen
self.cursor.execute(self.query)

Traceback:

    self.cursor.execute(self.query)
sqlite3.OperationalError: near ".": syntax error
like image 678
Kohonick Avatar asked Sep 23 '26 02:09

Kohonick


1 Answers

You need to read the file contents, and pass it to cursor.executescript() instead:

self.connection = sqlite3.connect(self.database)
self.cursor = self.connection.cursor()
with open(self.query) as queryfile:
    self.cursor.executescript(queryfile.read())

Your error shows you were trying to execute the filename as a SQL statement; cursor.execute() can only handle actual SQL strings, not filenames.

like image 97
Martijn Pieters Avatar answered Sep 24 '26 14:09

Martijn Pieters



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!