将列表写入Python数据库

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

Writing lists to database on python

问题

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

I have 3 lists with data like:

  1. frame1 = [{'CAR': 'MAZDA'}, {'CAR': 'Ferrari'}, {'CAR': 'BMW'}]
  2. frame2 = [{'country':'India'}, {'country':'Spain'}, {'country':'Mexico'}]
  3. frame3 = [{'year': '2022'}, {'year': '2021'}, {'year': '2020'}]

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

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

答案1

得分: 1

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

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

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.

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

答案2

得分: 0

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

  1. import sqlite3
  2. import pandas as pd
  3. with sqlite3.connect("foo.db") as conn:
  4. (pd.concat([pd.DataFrame(fr) for fr in [frame1, frame2, frame3]], axis=1)
  5. .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 :

  1. import sqlite3
  2. import pandas as pd
  3. with sqlite3.connect("foo.db") as conn:
  4. (pd.concat([pd.DataFrame(fr) for fr in [frame1, frame2, frame3]], axis=1)
  5. .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:

确定