您好,登錄后才能下訂單哦!
Python從MySQL數據庫中導出csv文件處理
csv文件導入MySQL數據庫
import pymysql import csv import codecs def get_conn(): conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='test_csv', charset='utf8') return conn def insert(cur, sql, args): cur.execute(sql, args) def read_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')
注:
1.csv文件的表頭如:
序號,合同編號,義務人,檔案柜號,柜內編號,權利人,放款金額,放款日期,他項權利證編號,抵押物地址,結清出庫日期,備注,地區
mysql的創建tb_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 def get_conn(): conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='test_csv', charset='utf8') return conn def query_all(cur, sql, args): cur.execute(sql, args) return cur.fetchall() def read_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文件從MySQL數據庫導入導出的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。