I'm currently trying to read through a csv file, take the contents of said csv file, and then put them into an sqlite3 database. I continually get a
OperationalError('near "s": syntax error')
Normally I would assume this to be a simple error somewhere in the culprit line of code.
The interesting thing is, however, that the program runs through 7 lines of the csv file before we hit this exception:
I check the following line in the csv file, which you can see here:
As far as I can tell, there are no 'abnormal' values there.
Finally, here is the full code:
def readData(filename, sqlite_file):
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
with open(filename) as CSVfile:
csvReader = csv.reader(CSVfile)
headers = next(csvReader)
for row in csvReader:
print(row[26] + ' ' + row[15] + ' ' + row[16] + ' ' + row[21] + ' ' + row[22] + ' ' + row[23] + ' ' + row[24] + ' ' + row[17])
tableName = 'Sponsor'
c.execute('INSERT INTO {tn} VALUES ({v1}, {v2}, {v3}, {v4}, {v5}, {v6}, {v7}, {v8})'.format(tn=tableName, v1=row[26], v2=str("'"+ row[15] +"'"), v3="'"+ row[16] +"'", v4="'"+ row[21] +"'", v5="'"+ row[22] +"'", v6= "'"+ row[23] +"'", v7= "'"+ row[24] +"'", v8= "'"+ row[17] +"'"))
If you format the query yourself you'll also need to handle quoting string arguments. Instead, you could just let the sqlite library do the heavy lifting for you and parameterize your statement. Note that object names cannot be parameterized, so you'll still have to format the table name in there:
c.execute('INSERT INTO {tn} VALUES (?, ?, ?, ?, ?, ?, ?, ?)'.format(tn=tableName),
[row[26], row[15], row[16], row[21], row[22], row[23], row[24], row[17]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.