Python之csv檔案從MySQL資料庫匯入匯出

2021-08-09 15:51:18 字數 2406 閱讀 1924

csv檔案匯入mysql資料庫

import pymysql

import csv

import codecs

defget_conn

(): conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='test_csv', charset='utf8')

return conn

definsert

(cur, sql, args):

cur.execute(sql, args)

defread_csv_to_mysql

(filename):

with codecs.open(filename=filename, mode='r', encoding='utf-8') as f:

reader = csv.reader(f)

head = next(reader)

conn = get_conn()

cur = conn.cursor()

sql = 'insert into tb_csv values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'

for item in reader:

if item[1] is

none

or item[1] == '': # item[1]作為唯一鍵,不能為null

continue

args = tuple(item)

print(args)

insert(cur, sql=sql, args=args)

conn.commit()

cur.close()

conn.close()

if __name__ == '__main__':

read_csv_to_mysql('1.csv')

注:

序號,合同編號,義務人,檔案櫃號,櫃內編號,權利人,放款金額,放款日期,他項權利證編號,抵押物位址,結清出庫日期,備註,地區
create

table tb_csv(

xuhao varchar(20),

htcode varchar(20),

yiwuren varchar(20),

dagh varchar(20),

gncode varchar(20),

quanliren varchar(20),

fkmoney varchar(20),

fkdata varchar(20),

qitacode varchar(20),

diyaaddr varchar(100),

jqdata varchar(30),

beizhu varchar(30),

zone

varchar(30),

primary

key(htcode)

)charset=utf8;

這裡為了省事,表中的字段都指明varchar型別

mysql資料庫寫入csv檔案

import pymysql

import csv

import codecs

defget_conn

(): conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='test_csv', charset='utf8')

return conn

defquery_all

(cur, sql, args):

cur.execute(sql, args)

return cur.fetchall()

defread_mysql_to_csv

(filename):

with codecs.open(filename=filename, mode='w', encoding='utf-8') as f:

write = csv.writer(f, dialect='excel')

conn = get_conn()

cur = conn.cursor()

sql = 'select * from tb_csv'

results = query_all(cur=cur, sql=sql, args=none)

for result in results:

print(result)

write.writerow(result)

if __name__ == '__main__':

read_mysql_to_csv('2.csv')

python學習之從csv檔案中讀取資料

python學習之將資料寫入到csv檔案中介紹了如何將記憶體中資料寫入到csv檔案中,這節將介紹如何從csv檔案中讀取資料,讀取資料也分為返回的是列表形式和字典形式 按行讀取,返回每行內容 import csv with open test.csv r encoding utf 8 as f f r...

Python之操作csv檔案

本篇僅作為 記錄 usr bin python coding utf 8 author ruiming lin datetime 2021 01 25 14 51 description import requests from pyquery import pyquery as pq import...

python之模組csv之CSV檔案一次寫入多行

coding utf 8 python 27 xiaodeng csv檔案一次寫入多行 import csv csv檔案,是一種常用的文字格式,用以儲存 資料,很多程式在處理資料時會遇到csv格式檔案 files open test.csv wb writer csv.writer files wr...