码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • python连接postgresql数据库及操作


    python连接postgresql数据库及操作

      • 1.python连接数据库
        • 1.1 安装相关库
        • 1.1 创建连接
        • 1.1 关闭连接
      • 2.python postgresql创建表
        • 2.1 创建连接
        • 2.2 创建事务提交函数
        • 2.3 创建表语句并调用函数
        • 2.4 关闭连接
      • 3.python postgresql批量插入表数据
        • 3.1 创建连接
        • 3.2 创建插入表数据函数
        • 3.3 读取表数据,调用函数
        • 3.4 关闭连接

    1.python连接数据库

    1.1 安装相关库

    pip install psycopg2
    pip install pandas 
    
    • 1
    • 2

    1.1 创建连接

    import psycopg2
    import pandas as pd
    conn = psycopg2.connect(database="postgres", user="postgres", password="", host="127.0.0.1", port="5432", client_encoding='utf-8')
    cursor = conn.cursor()
    
    • 1
    • 2
    • 3
    • 4

    1.1 关闭连接

    cursor.close()
    conn.close()
    
    • 1
    • 2

    2.python postgresql创建表

    2.1 创建连接

    import psycopg2
    import pandas as pd
    conn = psycopg2.connect(database="mapdb", user="postgres", password="", host="127.0.0.1", port="5432", client_encoding='utf-8')
    cursor = conn.cursor()
    
    • 1
    • 2
    • 3
    • 4

    2.2 创建事务提交函数

    def func_conn(conn,cursor,sql):
        try:  
            cursor.execute(sql)    
            conn.commit()        
            print("successfully")
        except Exception as e:   
            print('error',e) 
            conn.rollback()  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.3 创建表语句并调用函数

    sql= """CREATE TABLE climate
           (ID INT PRIMARY KEY NOT NULL,
           date date NOT NULL
    );"""
    func_conn(conn,cursor,sql)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.4 关闭连接

    cursor.close()
    conn.close()
    
    • 1
    • 2

    3.python postgresql批量插入表数据

    3.1 创建连接

    import psycopg2
    import pandas as pd
    from io import StringIO
    conn = psycopg2.connect(database="mapdb", user="postgres", password="", host="127.0.0.1", port="5432", client_encoding='utf-8')
    cursor = conn.cursor()
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.2 创建插入表数据函数

    conn = psycopg2.connect(host='127.0.0.1', user="postgres", password="", database="mapdb")
    cur = conn.cursor()
    def insert_table(data,table_name):
        try:
            f = StringIO()
            data.to_csv(f, sep='\t', index=False, header=False)
            f.seek(0)   
            cur.copy_from(f,table_name,columns=data.columns.to_list()) # 将内存对象f中的数据写入数据库,参数columns为所有列的元组
            conn.commit()
            f.close()
            print('成功写入数据库')
        except Exception as e:
            print(e)
            conn.rollback()
            f.close()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    3.3 读取表数据,调用函数

    # 注意:插入数据时,数据库中需要存在这张表
    data=pd.read_csv('data/data.csv')
    insert_table(data,'table_name')
    
    • 1
    • 2
    • 3

    3.4 关闭连接

    cursor.close()
    conn.close()
    
    • 1
    • 2
  • 相关阅读:
    [附源码]计算机毕业设计新冠疫苗接种预约系统Springboot程序
    面向对象特性之一:继承性
    ABAP 屏幕开发-仿采购订单
    为什么 GraphQL 可以取代 Redux?
    一起学数据结构(5)——栈和队列
    docker swam 集群实现负载均衡
    纵行科技携ZETA亮相世界物联网博览会,助力全球物联网生态合作
    网络工程师-宿主机桥接到华为eNSP中的路由器
    判断对象是否可以被回收:引用计数法,可达性分析,finalize()判定
    “华为杯”研究生数学建模竞赛2015年-【华为杯】A题:水面舰艇编队防空和信息化战争评估模型
  • 原文地址:https://blog.csdn.net/m0_46926492/article/details/127447958
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号