我试图在Python脚本中创建SQLite3中的新表(来自txt文件的数据)。我正在创建一个字符串作为将提供列标题的SQL命令。但是,当我将该字符串的变量插入到cursor.execute()中时,出现语法错误。事情是,如果我打印(),然后将其复制并粘贴到cursor.execute中,该脚本就可以工作。但是,我想对各种txt文件使用相同的脚本,因此它需要适应文件中的列标题。

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 "", line 1, in

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)的值直接复制并粘贴到代码中时,它可以工作。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐