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')

参见:http://blog.csdn.net/qq_33689414/article/details/78310689?locationNum=8&fps=1

https://www.cnblogs.com/rollenholt/archive/2012/05/29/2524327.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值