用Python 3將CSV匯入pycharm的sqlite

腫魔沒人留言?快點下去搶頭香啊!

建立table

在Pycharm設定好的sqlite中執行

CREATE TABLE members (
    id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
    name TEXT NOT NULL,
    group_name TEXT
);

CREATE TABLE draw_histories (
    memberid INTEGER,
    time DATETIME DEFAULT (datetime('now', 'localtime')),
    FOREIGN KEY(memberid) REFERENCES members(id)
);

將CSV匯入資料庫

import sqlite3
import csv

#因為路徑有特殊符號'\',所以要用r""表示,並且用utf-8讀取CSV檔案
with open(r"E:\git\test\members.csv", newline='', encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile)
    members = [
        (row['名字'], row['團體'])
        for row in reader
        ]

#identifier.sqlite是pycharm的預設sqlite資料庫名稱
db = sqlite3.connect('identifier.sqlite')
with db:
    db.executemany(
        'INSERT INTO  members (name, group_name) VALUES (?, ?)',
        members
    )

 

0 0 vote
Article Rating
訂閱(Subscribe)
來自於(Notify of)
0 Comments
Inline Feedbacks
View all comments