有没有办法使用从制表符分隔文件的标题中提取的变量来创建(SQL DB的)表名? 我试过这个:
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()
显然cur.execute
失败是因为调用变量的语法错误:
sqlite3.OperationalError: near "%": syntax error
任何人都可以帮助我吗?
答案 0 :(得分:1)
在注释行上的字符串后添加:
% (a, b, c)
更好的是,了解更新的字符串格式:https://mkaz.com/2012/10/10/python-string-format/
然后,一般来说,严格避免使用不受信任的字符串输入来构建SQL语句。