python使用dbutils连接PostgreSQL

安装好PostgreSQL后,开启本地服务,可通过Navicat连接数据库并导入excel数据项,注意数据库名、表名、字段名时均使用小写字母,如使用大写字母,在生成对应表名和字段会自动加上“”,影响查询,此外注意避开关键词,比如id,name,group之类SQL需要保留关键词。

如下为连接数据库代码

import psycopg2
# from  DBUtils.PooledDB import PooledDB # DBUtils 3.0.2版本无法使用,改为下列代码
from dbutils.pooled_db import PooledDB

POOL = PooledDB(
    creator=psycopg2,  # 使用链接数据库的模块
    maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
    mincached=2,  # 初始化时,链接池中至少创建的链接,0表示不创建
    blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    ping=0,  # ping SQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always

    host='127.0.0.1',
    port=5432,
    user='postgres',
    password='postgres',
    database='9000cw',
    # charset='utf8'
)


def fetchall(sql, *args):
    """ 获取所有数据 """
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute(sql, args)
    result = cursor.fetchall()
    cursor.close()
    conn.close()
    return result


def fetchone(sql, *args):
    """ 获取单行数据 """
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute(sql, args)
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    return result


if __name__ == "__main__":
    sql = 'SELECT * FROM personnel_information where name_= %S'
    result = fetchall(sql, '张三') # 需要注意这里只在筛选字段下可用,筛选表时不可用,
  # 合成的sql语句为SELECT * FROM personnel_information where name_= '张三', 多了前后单引号
print(result)

 在vscode测试运行时遇到中文显示乱码,改用cmd切换到对应目录,执行如下代码,测试显示正常。

Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。

尝试新的跨平台 PowerShell https://aka.ms/pscore6

PS F:\sql_连接postgres>    (这里运行python)


Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import 通过dbutils连接数据库 as db >>> db.fetchone('SELECT * FROM personnel_information where name_ = %s ' ,'张三') (365, '张三', '03246000', '产智项目部', None, 'zhangsan', 'zhangsan.SSC', 'zhangsan@163.com')

 附:修改数据库默认字符集

--修改客户端字符集
postgres=# show client_encoding;
 client_encoding 
-----------------
 UTF8
(1 row)

postgres=# set client_encoding='GBK';
SET

转自: https://blog.csdn.net/Tuanzidarendelaopo/article/details/81979004

 

posted @ 2022-06-17 23:21  毛绒绒  阅读(498)  评论(0编辑  收藏  举报