Python连接PostgreSQL数据库的方法

yipeiwu_com5年前Python基础

前言

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

连接数据库:

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

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))

总结

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

相关文章

python中将字典转换成其json字符串

#这是Python中的一个字典 dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': {...

python strip() 函数和 split() 函数的详解及实例

 python strip() 函数和 split() 函数的详解及实例 一直以来都分不清楚strip和split的功能,实际上strip是删除的意思;而split则是分割的意...

SublimeText 2编译python出错的解决方法(The system cannot find the file specified)

[Error 2] The system cannot find the file specified 解决方法:1.环境变量path添加:C:\Python32\Tools\Scrip...

PyCharm的设置方法和第一个Python程序的建立

PyCharm的设置方法和第一个Python程序的建立

1.代码编辑 字体大小设置 进入 File—》Settings—》Editor—》Colors & Fonts—》Font中。 首先要点击“Save as”然后为这个设置命名,我这里填入...

Python读写配置文件的方法

本文实例讲述了Python读写配置文件的方法。分享给大家供大家参考。具体分析如下: python 读写配置文件在实际应用中具有十分强大的功能,在实际的操作中也有相当简捷的操作方案,以下的...