使用python读取csv文件快速插入数据库的实例

yipeiwu_com5年前Python基础

如下所示:

# -*- 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第一列需要有列名,如果csv里没有列名,需要在代码中添加列名。

代码运行示例:python insert.py csvname tablename

以上这篇使用python读取csv文件快速插入数据库的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

OpenCV里的imshow()和Matplotlib.pyplot的imshow()的实现

OpenCV里的imshow()和Matplotlib.pyplot的imshow()的实现

一、问题 在Python里使用OpenCV时,一般是通过cv2.imread读入图片,然后用plt.imshow显示图片,但最近学习OpenCV时这样做的结果与预期的结果有较大的出入。查...

Python运用于数据分析的简单教程

Python运用于数据分析的简单教程

最近,Analysis with Programming加入了Planet Python。作为该网站的首批特约博客,我这里来分享一下如何通过Python来开始数据分析。具体内容如下: &...

python正常时间和unix时间戳相互转换的方法

本文实例讲述了python正常时间和unix时间戳相互转换的方法。分享给大家供大家参考。具体分析如下: 这段代码可以用来转换常规时间格式为unix时间戳,也可以将unix时间戳转换回来,...

python使用PIL模块获取图片像素点的方法

如下所示: from PIL import Image ########获取图片指定像素点的像素 def getPngPix(pngPath = "aa.png",pixelX =...

python中ConfigParse模块的用法

本文实例讲述了python中ConfigParse模块的用法,分享给大家供大家参考。具体方法如下: 写配置一般用ConfigParse.RawConfigParse类 读配置用Conf...