我正在解析以下文档。我还创建了一个带有表的虚拟sqlite3数据库。理想情况下,我想采用“print e”和“print f”语句,并将这些键作为列名插入。另外,我想拍摄“打印数据[e]”和“打印participant_data [f]”并将它们用作相应的值。我尝试了“插入表名值(?,?,?,?,?)”python代码,但我担心我不完全理解这一点。有谁知道如何通过python将这些行插入sqlite3中的泛型表?
数据:
{
"matchId": 1778839570,
"region": "NA",
"platformId": "NA1",
"matchMode": "CLASSIC",
"matchType": "MATCHED_GAME",
"matchCreation": 1427867835805,
"matchDuration": 3424,
"queueType": "RANKED_SOLO_5x5",
"mapId": 11,
"season": "SEASON2015",
"matchVersion": "5.6.0.194",
"participants": [
{
"teamId": 100,
"spell1Id": 4,
"spell2Id": 11,
"championId": 113,
"highestAchievedSeasonTier": "GOLD"
}
]
}
代码:
import sqlite3
import json
with open('data.json') as data_file:
data = json.load(data_file)
for e in data:
if e == 'participants':
participants_data=data['participants'][0]
print participants_data
for f in participants_data:
print f
print participants_data[f]
else:
print e
print data[e]
# # let's put this in sql
conn = sqlite3.connect('somedbname.sqlite')
c = conn.cursor()
#create_database
sql = 'create table if not exists tablename'
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
conn.commit()
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
conn.commit()
c.execute("select * from stocks")
print(c.fetchall())
编辑:第二次尝试代码:
import sqlite3
import json
with open('data.json') as data_file:
data = json.load(data_file)
for e in data:
if e == 'participants':
participants_data=data['participants'][0]
print participants_data
for f in participants_data:
print f
print participants_data[f]
else:
print e
print data[e]
api = data
# # let's put this in sql
conn = sqlite3.connect('somedbname.sqlite')
c = conn.cursor()
#create_database
sql = 'create table if not exists tablename'
c.execute('''CREATE TABLE if not exists stocks3
(col1 text, col2 text, col3 text, col4 text, col5 text, col6 text, col7 text, col8 text, col9 text, col10 text, col11 text, col12 text)''')
conn.commit()
c.execute("INSERT INTO stocks3 VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", api)
conn.commit()
c.execute("select * from stocks")
print(c.fetchall())