Is there a way to create the table name (of a SQL DB) with variables extracted from the header of a tab delimited file ? I have try this:
import sqlite3
conn = sqlite3.connect('cur_test.sq3')
cur = conn.cursor()
#Create a 'test.txt' file for that example
test = open('test.txt', 'w')
test.write('a\t1\t2\n')
test.close()
#REMEMBER: header of test.txt = a 1 2 (tab delimited)
with open('test.txt') as f:
header = f.readline().rstrip("\n") #Extract the header
a, b, c = header.split("\t") #Split it into variable
b, c = int(b), int(c) #Convert some string into integer
req = "CREATE TABLE test (%s TEXT, %s INTEGER, %s INTEGER)" #I need help here
cur.execute(req, (a, b, c))
conn.commit()
Obviously the cur.execute
fail because of the wrong syntax for calling the variables:
sqlite3.OperationalError: near "%": syntax error
Can anyone help me ?
Add this after the string on your commented line:
% (a, b, c)
Better yet, read about the newer style of string formatting: https://mkaz.com/2012/10/10/python-string-format/
And then, generally speaking, strictly avoid using untrusted string input to build SQL statements.
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.