目录
4、使用python的configparser包来解析配置文件
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秒。