在sqlite3中动态创建和执行INSERT命令

时间:2018-03-14 07:04:34

标签: python python-3.x sqlite


我正在尝试构建一个用于sqlite3的SQL查询 然而,我使用for循环根据所需的特定参数构造查询
当我尝试为查询运行execute时,我很遗憾地收到错误:

  

c.execute(sql_query)   sqlite3.OperationalError:接近“'''INSERT INTO myTable(”ID“,”1“,”2“)VALUES(?,?,?)'''”:语法错误

这是完整的代码。

import sqlite3, os, re

conn = create_connection(db)
c = conn.cursor()

######### BUILDING SQL QUERY ##############
for file in os.listdir(objExp):
    # Go through each file in the directory, split to remove file extension
    fileID = file.split('.')[0]
    raw_in = input("What values should " + fileID + " have?\n") # input values for this file each seperated by a comma
    num_vals = len(raw_in.split(',')) # Calculate number of values assigned for this file

    if (len(raw_in) == 0):
        # No values to be assigned to this fileID - just add to database with default value (0)
        sql_query = "'''INSERT INTO myTable(\"ID\") VALUES(?)''', (fileID)"
    else:
        # All other cases - meticulously build each section of sqlite3 SQL command
        raw_in = "\"" + raw_in
        raw_in = raw_in + "\""
        raw_in = re.sub(',', '\", \"', raw_in)
        # Values
        values = "VALUES(?,"
        var_chain = "(fileID, "
        for i in range(0,num_vals):
            values = values + "?,"
            var_chain = var_chain + "1, "

        values = re.sub(',$', ')', values)
        var_chain = re.sub(', $', ')', var_chain)
        sql_query = "'''INSERT INTO myTable(\"ID\", " + raw_in + ") " + values + " ''', " + var_chain        
######### END BUILDING SQL QUERY ##############

    print(sql_query)
    c.execute(sql_query)
    conn.commit()

conn.close()

构建SQL查询的代码(在##### ######之间)是正确的。我已经单独测试了这个 我查看了executemany,但我不确定它是否有效,因为VALUES(?....)的长度在我的情况下总是在变化。

提前致谢!

0 个答案:

没有答案