使用python读取csv文件快速插入数据库的实例
如下所示:
#-*-coding:utf-8-*- #auth:ckf #date:20170703 importpandasaspd importcStringIO importwarnings fromsqlalchemyimportcreate_engine importsys reload(sys) sys.setdefaultencoding('utf8') warnings.filterwarnings('ignore') engine=create_engine( 'postgresql+psycopg2://'数据库连接) filename=sys.argv[1] tablename=sys.argv[2] print'===csvnameis',filename,'tablenameis',tablename,'===' print'read',filename,'...' df=pd.read_csv(filename,sep=';') print'read',filename,'done!' print'letsinsert...' output=cStringIO.StringIO() #ignoretheindex df.to_csv(output,sep='\t',index=False,header=False) output.getvalue() #jumptostartofstream output.seek(0) connection=engine.raw_connection() cursor=connection.cursor() #nullvaluebecome'' cursor.copy_from(output,tablename,null='') connection.commit() cursor.close() print'done!'
这个脚本可以直接运行,将csv文件放在同级目录即可。
csv第一列需要有列名,如果csv里没有列名,需要在代码中添加列名。
代码运行示例:pythoninsert.pycsvnametablename
以上这篇使用python读取csv文件快速插入数据库的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。