Python 如何将百万数据入PostgreSQL库

1. PostgreSQL 是什么

PostgreSQL 是一个功能强大的开源对象关系型数据库系统,他使用和扩展了SQL语言,并结合了许多安全存储和扩展最复杂数据工作负载的功能。

PostgreSQL 的起源可以追溯到1986年,作为加州大学伯克利分校POSTGRES项目的一部分,并且在核心平台上进行了30多年的积极开发。

PostgreSQL 凭借其经过验证的架构,可靠性,数据完整性,强大的功能集,可扩展性以及软件背后的开源社区的奉献精神赢得了良好的声誉,以始终如一地提供高性能和创新的解决方案。

2. 业务驱动选择 PostgreSQL

由于业务在做压测时需要灌入大量的测试数据,试过很多方式都没有很好解决,最终选择用 Python 来实现数据灌入到 PostgreSQL,粗估数据处理效率可达6.5W/s.

3. Python代码实现

代码里面有一个 batchs 的参数,用来控制批量插入数据库批次,目前给的1000,效果还是十分不错的。

代码如下:

from openpyxl import load_workbook
import random
import psycopg2
batchs =1000

def data(datas):
    conn = None
    try:
        conn = psycopg2.connect(database="test_62554cf827ca24dc542c4258", user="postgres", password="123456",
                                host="10.10.11.248", port="5432")
        print("connected to postgres db successfully")
    except:
        print("I am unable to connect to the database")
    try:
        cursor = conn.cursor()
        sql = "insert into t_fact_6260d12dcd211247f807e521 values " + datas+";"
        print(sql)
        cursor.execute(sql)
    except (Exception, psycopg2.Error) as error:
        print("Error caught", error)
    finally:
        conn.commit()
        if (conn):
            cursor.close()
            conn.close()

def insertData():
    count = 0
    lw=load_workbook(r'D:\wl\bussiness_study\testdata.xlsx', read_only='read_only')
    ws = lw.active
    print(ws.rows)
    lst=[]
    strs = ""
    for row in ws.rows:
        count += 1
        lst.append("111"+str(random.random()))
        lst.append(0)
        lst.append("1634745600.0")
        lst.append("513567da-2d61-41db-a4cb-f2"+str(random.randint(100000000,999999999)))
        for col in row:
            lst.append(col.value)
        print("执行第--%d--行" % (count))
        # print(lst)
        str2 = str(tuple(lst)).replace("None", "'None'")+","
        # print(str2)
        if(count%batchs==0):
            strs += str2
            # print(strs)
            data(strs[:-1])
            lst = []
            strs = ""
            count=0
        else:
            strs += str2
            # print(strs)
            lst=[]
        str2 = ""
        # print(strs)

if __name__ == '__main__':
    insertData()

欢迎关注【无量测试之道】公众号,回复【领取资源】

Python+Unittest框架API自动化、

Python+Unittest框架API自动化、

Python+Pytest框架API自动化、

Python+Pandas+Pyecharts大数据分析、

Python+Selenium框架Web的UI自动化、

Python+Appium框架APP的UI自动化、

Python编程学习资源干货、

Vue前端组件化框架开发、

资源和代码 免费送啦~
文章下方有公众号二维码,可直接微信扫一扫关注即可。

备注:我的个人公众号已正式开通,致力于IT互联网技术的分享。

包含:数据分析、大数据、机器学习、测试开发、API接口自动化、测试运维、UI自动化、性能测试、代码检测、编程技术等。

微信搜索公众号:“无量测试之道”,或扫描下方二维码:

  在这里插入图片描述

 添加关注,让我们一起共同成长!

猜你喜欢

转载自blog.csdn.net/weixin_41754309/article/details/125349867