簡體   English   中英

Python,將XML數據插入sqlite3

[英]Python, insert XML data to sqlite3

我試圖從URL中提取一些XML,解析它並將條目存儲在sqlite3數據庫中,我嘗試了很多事情,但都失敗了。 到目前為止,科德:

#!/usr/bin/env python

from urllib2 import urlopen
import gc
import xml.etree.ElementTree as ET
import sqlite3

rosetta_url = ("https://boinc.bakerlab.org/rosetta/team_email_list.php?teamid=12575&account_key=Y&xml=1")

root = ET.parse(urlopen(rosetta_url)).getroot()
cpids = [el.text for el in root.findall('.//user/cpid')]
print cpids

conn = sqlite3.connect("GridcoinTeam.db")
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS GRIDCOINTEAM (cpid TEXT)''') 
c.executemany("INSERT INTO GRIDCOINTEAM VALUES (?);", cpids)
conn.commit()       
conn.close()

conn = sqlite3.connect("GridcoinTeam.db")
c = conn.cursor()
cpids = c.execute('select cpid from GRIDCOINTEAM').fetchall()
conn.close()

print cpids

gc.collect()

我收到錯誤:

Incorrect number of bindings supplied. The current statement uses 1, and there are 32 supplied.

我嘗試通過更改為插入元組

c.executemany("INSERT INTO GRIDCOINTEAM VALUES (?);", (cpids, ))

但這只是給:

Incorrect number of bindings supplied. The current statement uses 1, and there are 3289 supplied.

XML提取形式為['5da243d1f47b7852d372c51d6ee660d7','5a6d18b942518aca60833401e70b75b1','527ab53f75164864b74a89f3db6986b8'],但其中有數千個條目。

謝謝。

您需要將其作為多行而不是多列插入到一行中

cpids = [el.text for el in root.findall('.//user/cpid')]
cpids = zip(*[iter(cpids)]*1)
print cpids

問題出在

c.executemany("INSERT INTO GRIDCOINTEAM VALUES (?);", cpids)

這個executemany需要一個元組列表,但是您傳遞一個字符串列表。 該代碼有效執行的操作是:

for entry in cpids:
    c.execute("INSERT INTO GRIDCOINTEAM VALUES (?);", *entry)

注意之前的明星entry ,其卸載字符串,它給你32+ PARAMS而你只想要一個。

為了解決這個問題,我們需要了解您的GRIDCOINTEAM表架構。 如果您的表只有一列,並且要插入該列,則可以執行以下操作:

for entry in cpids:
    c.execute("INSERT INTO GRIDCOINTEAM VALUES (?)", entry)

executemany相反, execute將每個參數作為一個參數-沒有元組,並在此處列出要卸載的參數。

另外,您可以使用executemany ,但隨后需要將每個字符串包裝在元組或生成器中:

c.executemany("INSERT INTO GRIDCOINTEAM VALUES (?);", [(i,) for i in cpids])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM