Python连接PostgreSQL数据库的方法

时间:2022-06-15 19:53:07

前言

其实在Python中可以用来连接PostgreSQL的模块很多,这里比较推荐psycopg2。psycopg2安装起来非常的简单(pip install psycopg2),这里主要重点介绍下如何使用。

连接数据库

?
1
2
import psycopg2
conn = psycopg2.connect(host="10.100.157.168",user="postgres",password="postgres",database="testdb")

连接时可用参数:

     dbname – 数据库名称 (dsn连接模式)

     database – 数据库名称

     user – 用户名

     password – 密码

     host – 服务器地址 (如果不提供默认连接Unix Socket)

     port – 连接端口 (默认5432)

执行SQL

?
1
2
3
4
5
6
7
8
import psycopg2
 
conn = psycopg2.connect(host="10.100.157.168",port=5432,user="postgres",password="postgres",database="testdb")
cur = conn.cursor()
sql = ""
cur.execute(sql)
conn.commit() # 查询时无需,此方法提交当前事务。如果不调用这个方法,无论做了什么修改,自从上次调用#commit()是不可见的
conn.close()

另外执行SQL时支持参数化

语法: cursor.execute(sql [, optional parameters])

案例: cursor.execute("insert into people values (%s, %s)", (who, age))

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

原文链接:http://www.biaodianfu.com/python-postgresql.html?utm_source=tuicool&utm_medium=referral