我试图在Python脚本中的SQLite3(来自txt文件的数据)中创建一个新表 . 我正在创建一个字符串,用作将给出列 Headers 的SQL命令 . 但是,当我将此字符串的变量插入cursor.execute()时,我收到语法错误 . 问题是,如果我打印()然后将其复制并粘贴到cursor.execute中,则脚本可以正常工作 . 但是,我想对各种txt文件使用相同的脚本,因此需要适应文件中的列 Headers .
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()
这会产生:
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
但是,当我将print(daQuery)的值直接复制并粘贴到代码中时,它可以工作 .
1 回答
看起来你已经使用了单引号和双引号 . 试试这样: