当前位置:首页 >> 脚本专栏

Python之csv文件从MySQL数据库导入导出的方法

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数据库导入导出的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。