python postgresql 数据库操作库 psycopg2 简介

目录

1、连接数据库

2、关闭数据库

3、cursor类

4、使用python的configparser包来解析配置文件

5.设置超时

5-1.执行超时

方法1

方法2

5-2.连接超时


1、连接数据库

try :
	conn = psycopg2.connect(database='postgres', user='postgres',
	password='ssss', host='127.0.0.2', port=6666)
except Exception as e:
    print('连接数据库失败!')

2、关闭数据库

# 连接数据库,执行了sql语句,以及进行完所有其他操作之后需要提交事务并且关闭数据库
# 提交事务
conn.commit()
# 关闭连接
conn.close()

3、cursor类

# psycopy2提供了一个cursor类,用来在数据库Session里执行PostgresSQL命令。

# 创建cursor对象:
cursor = conn.cursor() 

# 使用cursor对象来执行SQL语句。
cursor.execute(sql)

# 执行SQL命令后的返回结果由cursor.fetchall()接收为一个元祖的列表。
lines = cursor.fetchall()
# 例如
select timeline FROM "public".org_target_job_record WHERE target_job = 'ETL' and target_type = '本品' ORDER BY timeline DESC LIMIT 1
# 查询到的结果是20220103,cursor.fetchall()接收到的列表是这样。
# [('20220103',)]
# 使用lines[0][0]来取到第一个数字。

# 关闭cursor对象
cursor.close()

4、使用python的configparser包来解析配置文件

# ConfigParser 是用来读取配置文件的包
# 导入并且初始化
import configparser
config = configparser.ConfigParser()
# 读取配置文件
config.read("ini", encoding="utf-8")

# 假设配置文件如下
[db]
db_host = 127.0.0.2
db_port = 66
db_user = root
db_pass = root
host_port = 66

# 常用方法

# 获取所有的sections,‘[]’内包含的即为section。
config.sections()
# 返回列表,即 ['db']

# 获取指定section下指定的option值
config.options('db')
# 返回一个列表 
# ['db_host', 'db_port', 'db_user', 'db_pass', 'host_port']

# 获取到指定option的值
config['db']['db_host']

# 更多功能请参考链接文章

5.设置超时

5-1.执行超时

方法1

import psycopg2
cnn = psycopg2.connect("dbname=test options='-c statement_timeout=1000'")
cur = cnn.cursor()
cur.execute("select pg_sleep(2000)")

执行结果:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
psycopg2.extensions.QueryCanceledError: canceling statement due to statement timeout

方法2

import os
os.environ['PGOPTIONS'] = '-c statement_timeout=1000'
import psycopg2
cnn = psycopg2.connect("dbname=test")
cur = cnn.cursor()
cur.execute("select pg_sleep(2000)")

执行结果:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
psycopg2.extensions.QueryCanceledError: canceling statement due to statement timeout

5-2.连接超时

db = psycopg2.connect (
    host=dhost, database=ddatabase,
    user=duser, password=dpassword,
    connect_timeout=3
)

connect_timeout 选项

连接时的最大等待时间,以秒为单位(写为十进制整数,例如10)。0、负数或未指定表示无限期等待。允许的最小超时时间是2秒,因此值1被解释为2。此超时时间分别适用于每个主机名或IP地址。例如,如果指定两个主机,连接超时时间为5,那么如果在5秒内没有连接,则每个主机都将超时,因此等待连接的总时间可能高达10秒。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值