将数据库中的所有表导出到python中的单个csv文件中

时间:2016-06-16 02:16:15

标签: python mysql csv

我一直在尝试将数据库中所有表格导出到单个csv文件中。

我已经尝试了

import MySQLdb as dbapi
import sys
import csv
import time


dbname      = 'site-local'
user        = 'root'
host        = '127.0.0.1'
password    = ''
date        = time.strftime("%d-%m-%Y")
file_name   = date+'-portal'

query='SELECT * FROM site-local;' //<---- I'm stuck here

db=dbapi.connect(host=host,user=user,passwd=password)
cur=db.cursor()
cur.execute(query)
result=cur.fetchall()

c = csv.writer(open(file_name+'.csv','wb'))
c.writerow(result)

我现在有点陷入困境,我希望有人可以根据我所拥有的内容做一些基础。

2 个答案:

答案 0 :(得分:2)

使用python不是解决这个问题的方法。最简单的解决方案是使用SELECT INTO OUTFILE。这样就可以快速地将非常大的表转储成CSV格式,而无需在python代码中使用CSV编写器。

根据您的其他问题,我了解您转储的原因是重新导入到postgresql中。如果不是这样,您可以简单地使用mysqldump命令立即转储整个数据库。

如果要以CSV格式转储每个表,它会调用一些代码。创建一个python循环来迭代所有表,然后对每个表执行SELECT INTO查询。

答案 1 :(得分:1)

考虑从所有数据库表中迭代导出SHOW CREATE TABLE(txt文件)和SELECT * FROM(csv文件)输出。根据您之前的相关问题,由于您需要迁移数据库,因此您可以运行create table语句(调整MySQL for Postgre语法,如ENGINE=InnoDB行),然后使用PostgreSQL通过csv导入数据&#39; s COPY命令。 csv文件下面包含fetchall()中未包含的表格列标题。

db = dbapi.connect(host=host,user=user,passwd=password)
cur = db.cursor()

# RETRIEVE TABLES
cur.execute("SHOW TABLES")
tables = []
for row in cur.fetchall():
    tables.append(row[0])

for t in tables:    
    # CREATE TABLES STATEMENTS
    cur.execute("SHOW CREATE TABLE `{}`".format(t))
    temptxt = '{}_table.txt'.format(t)

    with open(temptxt, 'w', newline='') as txtfile:
        txtfile.write(cur.fetchone()[1])                   # ONE RECORD FETCH
    txtfile.close()

    # SELECT STATEMENTS
    cur.execute("SELECT * FROM `{}`".format(t))
    tempcsv = '{}_data.csv'.format(t)

    with open(tempcsv, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow([i[0] for i in cur.description])   # COLUMN HEADERS
        for row in cur.fetchall():        
            writer.writerow(row)
    csvfile.close()

cur.close()
db.close()
相关问题