菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
499
0

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

原创
05/13 14:22
阅读数 595545

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

(一)psycopg2

ubuntu下安装

sudo apt-http://www.cppcns.comget 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.cursorhttp://www.cppcns.com()
cur.execute("SEL编程客栈ECT * 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/数据库名www.cppcns.com')
db = postgresql.open('pq://jm:123@localhost:5432/test1')
ps=db.prepare("select * from a1")
print(ps())
ps.close()
db.close()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

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

本文标题: Python实现连接postgresql数据库的方法分析
本文地址: http://www.cppcns.com/shujuku/postgresql/215837.html

发表评论

0/200
499 点赞
0 评论
收藏
为你推荐 换一批