服务器之家

服务器之家 > 正文

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

时间:2021-03-07 00:45     来源/作者:chenKFKevin

如下所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*- 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文件快速插入数据库的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/chenKFKevin/article/details/74247979

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部