zoukankan      html  css  js  c++  java
  • python连接postgresql数据库

    python可以通过第三方模块连接postgresql. 比较有名的有psycopg2  和python3-postgresql

    (一)psycopg2

    ubuntu下安装

    sudo apt-get install python3-psycopg2

    创建一个test.py文件

    import psycopg2
    # 数据库连接参数
    conn = psycopg2.connect(database="test1", user="jm", password="123", host="127.0.0.1", port="5432")
    cur = conn.cursor()
    
    cur.execute("SELECT * FROM a1;")
    rows = cur.fetchall()        # all rows in table
    print(rows)

     conn.commit()
     cur.close()
     conn.close()

     

    运行后显示如下

    [(2, 'jack', 'girl'), (1, 'max', 'boy '), (3, 'kate', 'girl')]

    (二)python3-postgresql

    ubuntu下安装

    sudo apt-get install python3-postgresql

     创建文件并运行

    import postgresql
    
      #('pq://用户名:密码@localhost:5432/数据库名')
    db = postgresql.open('pq://jm:123@localhost:5432/test1')
    ps=db.prepare("select * from a1")
    
    print(ps())
    
    ps.close()
    db.close()
  • 相关阅读:
    MAX导致数据库超时
    mysql查询效率提高技巧
    微信回调报文解析, 获取请求体内容
    炖汤秘方
    首字母小写
    List分页
    HttpServletRequest通过InputStream获取参数
    github命令行
    mysql死锁
    分布式锁-redis
  • 原文地址:https://www.cnblogs.com/jmlovepython/p/5023794.html
Copyright © 2011-2022 走看看