文档中心MogDBMogDB StackUqbar
v5.0

文档:v5.0

支持的版本:

其他版本:

示例:常用操作

基本操作

import psycopg2

# psycopg2常用连接方式
1. conn = psycopg2.connect(dbname="postgres", user="user", password="password", host="localhost", port=port)
2. conn = psycopg2.connect("dbname=postgres user=user password=password  host=localhost port=port")


# 创建连接对象
conn=psycopg2.connect(database="postgres",user="user",password="password",host="localhost",port=port)
cur=conn.cursor() #创建指针对象

# 创建连接对象(SSl连接)
conn = psycopg2.connect(dbname="postgres", user="user", password="password", host="localhost", port=port,
         sslmode="verify-ca", sslcert="client.crt",sslkey="client.key",sslrootcert="cacert.pem")
注意:sslcert,sslkey,sslrootcert分别为用户证书,用户私钥和根证书的文件路径,如果不进行赋值,默认为
      ~/.postgresql目录下对应的client.crt,client.key和root.crt。


# 创建表
cur.execute("CREATE TABLE student(id integer,name varchar,sex varchar);")

#插入数据
cur.execute("INSERT INTO student(id,name,sex) VALUES(%s,%s,%s)",(1,'Aspirin','M'))
cur.execute("INSERT INTO student(id,name,sex) VALUES(%s,%s,%s)",(2,'Taxol','F'))
cur.execute("INSERT INTO student(id,name,sex) VALUES(%s,%s,%s)",(3,'Dixheral','M'))

# 获取结果
cur.execute('SELECT * FROM student')
results=cur.fetchall()
print(results)

# 关闭连接
conn.commit()
cur.close()
conn.close()

with 语法

当连接退出 with 块时,如果该块没有引发异常,则事务被提交。在异常情况下,事务被回滚。

当游标退出 with 块时,它被关闭,释放最终与它关联的所有资源。事务的状态不受影响。

一个连接可以在多个 with 语句中使用,每个 with 块都有效地包装在一个单独的事务中:

conn = psycopg2.connect(DSN)

with conn:
    with conn.cursor() as curs:
        curs.execute(SQL1)

with conn:
    with conn.cursor() as curs:
        curs.execute(SQL2)

conn.close()

提醒:与文件对象或其他资源不同,退出连接的 with 块不会关闭连接,只会关闭与之相关的事务。如果你想确保连接在某一点后关闭,你仍然应该使用 try-catch 块:

conn = psycopg2.connect(DSN)
try:
    # connection usage
finally:
    conn.close()

使用日志

import logging
import psycopg2
from psycopg2.extras import LoggingConnection

logging.basicConfig(level=logging.DEBUG) # 日志级别
logger = logging.getLogger(__name__)

db_settings = {
    "user": "user",
    "password": "password",
    "host": "localhost",
    "database": "postgres",
    "port": port
}
conn = psycopg2.connect(connection_factory=LoggingConnection, **db_settings)
conn.initialize(logger)
Copyright © 2011-2024 www.enmotech.com All rights reserved.