Python利用pandas与SQLAlchemy快速将CSV数据导入数据库
本文介绍如何使用Python脚本结合pandas库与SQLAlchemy引擎,实现将本地CSV文件快速批量插入数据库的功能。脚本通过命令行接收文件名和表名,利用copy_from方法高效处理数据写入,适用于PostgreSQL等支持COPY命令的数据库场景。
具体实现方案如下所示:
# -*- coding:utf-8 -*-
# auth:ckf
# date:20170703
import pandas as pd
import cStringIO
import warnings
from sqlalchemy import create_engine
import sys
reload(sys)
sys.setdefaultencoding('utf8')
warnings.filterwarnings('ignore')
engine = create_engine(
'postgresql+psycopg2://'数据库连接)
filename = sys.argv[1]
tablename = sys.argv[2]
print '=== csvname is',filename ,'tablename is',tablename,'==='
print 'read', filename, '...'
df = pd.read_csv(filename, sep=';')
print 'read', filename, 'done!'
print 'lets insert ...'
output = cStringIO.StringIO()
# ignore the index
df.to_csv(output, sep='\t',index = False, header = False)
output.getvalue()
# jump to start of stream
output.seek(0)
connection = engine.raw_connection()
cursor = connection.cursor()
# null value become ''
cursor.copy_from(output,tablename,null='')
connection.commit()
cursor.close()
print 'done!'
该脚本支持直接运行,只需确保待处理的CSV文件与脚本位于同一目录下即可。
若CSV文件第一列未包含列名,则需在代码中显式指定列名信息。
执行示例命令为:python insert.py csvname tablename
以上即为使用Python读取CSV文件并快速插入数据库的完整示例,希望能为读者提供有价值的参考。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









