当前位置: 移动技术网 > IT编程>脚本编程>Python > Python实现连接postgresql数据库的方法分析

Python实现连接postgresql数据库的方法分析

2018年02月15日  | 移动技术网IT编程  | 我要评论

蕴奇支付,尹喜地的车,具体而微造句

本文实例讲述了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()

更多关于Python相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》

希望本文所述对大家Python程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网