zoukankan      html  css  js  c++  java
  • 使用python读取csv文件快速插入数据库的实例

    如下所示:

    # -*- 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='	',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

  • 相关阅读:
    GSON -JSON 反序列化-多节点名称支持
    Jedis 分片原理
    闭锁-CountDownLatch
    XML序列化及反序列化
    用GIT操作SVN
    报表worker-CPU使用率过高原因排查
    二.PlantUML 之活动图
    一.PlantUML 与 IDEA 集成
    ArrayList
    VI常用命令
  • 原文地址:https://www.cnblogs.com/zaixiachengxuyuan/p/14465692.html
Copyright © 2011-2022 走看看