I am trying to create a new table in SQLite3 (data coming from a txt file) in a Python script. I am creating a string to use as the SQL command that will give the column headers. However, when I insert the variable for this string into the cursor.execute() I get a syntax error. The thing is, if I print() and then copy and paste that into the cursor.execute, the script works. However, I want to use this same script for various txt files, so it needs to adapt to the column headers in the file.
def CreateTable (daDB, daFile, daTableName): #Creates a table with column headers as first row of file
con=sqlite3.connect(daDB)
curs=con.cursor()
LinesList=FileReadIn(daFile)
Headers=LinesList[0]
HeadersString=""
for word in Headers:
HeadersString += word + ", "
DaHeadersString=HeadersString[0:-2]
daQuery="'create table " + daTableName + " (" + DaHeadersString + ")'"
print (daQuery)
curs.execute(daQuery)
con.commit()
con.close()
This generates:
CreateTableFromText ('animalsheaderstest.sqltdb','animals.txt','animalstable')
'create table animalstable (Owner, Name, Species)'
Traceback (most recent call last):
File "<pyshell#108>", line 1, in <module>
CreateTable ('animalsheaderstest.sqltdb','animals.txt','animalstable')
File "/Users/zeintawil/Zeins_Files/School/Senior/OPIM_399/python/practice/ReadInPrac.py", line 62, in CreateTable
curs.execute(daQuery)
OperationalError: near "'create table animalstable (Owner, Name, Species)'": syntax error
However, when I copy and paste the value of print(daQuery) directly into the code, it works.
Looks like you have used both single and double quotes. Try like this: