使用executemany

时间:2017-07-26 19:34:08

标签: python sqlite

我正在创建一个数据库并插入从Excel工作表创建的列表列表。主列表是使用openpyxl创建的,然后该列表每18个项目拆分为一个列表列表。我想将所有项目插入数据库。不太熟悉SQL,但经过一些研究,我设法把它放在一起:

import sqlite3
from openpyxl import load_workbook
import os
filepath = os.path.expanduser("~\Desktop\\")
data1 = []
data=[]
wb1 = load_workbook(filename=filepath+"exportUL1.XLSX")
ws1 = wb1['Sheet1']                         ###call the worksheet with the data

x = 0 
for row in ws1.iter_rows():
                                        #look for the correct value, "Q" and return all the data in that row to the data list
    for cell in row:
        if cell.value == 'Q':
            data.append(x)              #append the id numbers to the list
            for cell in row:
                data.append(str(cell.value))   #append the row data to the list
    x += 1

data_lists = [data[x:x+18] for x in range(0, len(data),18)]     #convert list to list of lists, split every 18 items

conn = sqlite3.connect('test.db')
print "Opened database successfully";
with conn:
    cur = conn.cursor()

    cur.execute('''CREATE TABLE QualityHold(
    Id Int,StorageLocation TEXT, StorageType TEXT, StorageBin TEXT, StorageUnit TEXT,
    Material TEXT, Plant TEXT, Batch TEXT, StockCategory TEXT, SpecialStock TEXT, SpecialStockNumber TEXT,            
    Duration TEXT, PutawayBlock TEXT, StockRemovalBlock TEXT, AvailableStock TEXT, StockforPutaway TEXT,
    PickQuantity TEXT, TotalStock TEXT)''')                                                                   #create the table with these headers

    sql = '''INSERT INTO QualityHold (Id,StorageLocation, 
     StorageType, StorageBin, StorageUnit, Material, 
     Plant, Batch, StockCategory, SpecialStock, 
     SpecialStockNumber, Duration, PutawayBlock, StockRemovalBlock,
     AvailableStock, StockforPutaway, PickQuantity, TotalStock)  
     VALUES 
     (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'''#sql command

    cur.executemany(sql,data_lists)###execute the sql command using the list of lists for the variables(LINE 38)

conn.close()

运行后,我收到以下错误

Traceback (most recent call last):
  File "C:\Users\ONP1LDY\eclipse-workspace\WOrk\QualityInspection.py", line 38, in <module>
    cur.executemany(sql,data_lists)
sqlite3.OperationalError: near "%": syntax error

任何可能导致这种情况的帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

我走了另一条路线,用以下内容取代了executemany:

for lst in data_lists:
    var_string = ', '.join('?'*len(lst))
    query_string = 'INSERT OR IGNORE INTO QualityHold VALUES (%s);' % var_string
    cur.execute(query_string, lst)