将列表写入Python数据库

huangapple go评论64阅读模式
英文:

Writing lists to database on python

问题

    CAR   | country | year
1 | MAZDA |  India  | 2022
2 |Ferrari|  Spain  | 2021
3 |  BMW  |  Mexico | 2020
英文:

I have 3 lists with data like:

frame1 = [{'CAR': 'MAZDA'}, {'CAR': 'Ferrari'}, {'CAR': 'BMW'}]

frame2 = [{'country':'India'}, {'country':'Spain'}, {'country':'Mexico'}]

frame3 = [{'year': '2022'}, {'year': '2021'}, {'year': '2020'}]

I want to write lists to a database in the form:

    CAR   | country | year
______________________________
1 | MAZDA |  India  | 2022
2 |Ferrari|  Spain  | 2021
3 |  BMW  |  Mexico | 2020

答案1

得分: 1

使用zip()并行循环遍历列表。然后将字典元素组合成元组,使用executemany()将它们全部插入表中。

sql = 'INSERT INTO tableName (car, country, year) VALUES (?, ?, ?)'
cursor.executemany(sql, 
    ((v1['CAR'], v2['country'], v3['year']) 
     for v1, v2, v3 in zip(frame1, frame2, frame3))
)
英文:

Use zip() to loop over the lists in parallel. Then combine the dictionary elements into a tuple, and use executemany() to insert all of them into the table.

sql = 'INSERT INTO tableName (car, country, year) VALUES (?, ?, ?)'
cursor.executemany(sql, 
    ((v1['CAR'], v2['country'], v3['year']) 
     for v1, v2, v3 in zip(frame1, frame2, frame3))
)

答案2

得分: 0

你的问题似乎对我来说有点模糊(至少对我来说是这样)。
但作为一个起点,使用 [tag:pandas],你可以使用 concat/to_sql

import sqlite3
import pandas as pd

with sqlite3.connect("foo.db") as conn:
    (pd.concat([pd.DataFrame(fr) for fr in [frame1, frame2, frame3]], axis=1)
         .to_sql("table", conn, if_exists="fail", index=False)) #在这里调整参数

输出:

将列表写入Python数据库

英文:

Your question seems too vague (at least for me).
But as a starting point, with [tag:pandas], you can use concat/to_sql :

import sqlite3
import pandas as pd

with sqlite3.connect("foo.db") as conn:
    (pd.concat([pd.DataFrame(fr) for fr in [frame1, frame2, frame3]], axis=1)
         .to_sql("table", conn, if_exists="fail", index=False)) #adjust the params here

Output :

将列表写入Python数据库

huangapple
  • 本文由 发表于 2023年4月20日 01:55:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定