python连接PostgreSQL

1.pip
pip是python管理第三方包的工具,在python3中自带,安装完成就可以用,只是默认名字带来版本号 ,/usr/local/bin/pip3.10
所以先给它起个别名 叫pip,用起来方便些,命令如下

ln -s /usr/local/bin/pip3.10 /usr/bin/pip

2.下载pg的连接库

pip install psycopg2-binary

3.写一段的代码测试一下

#!/usr/bin/python
import psycopg2
def connect():
    conn = None
    try:        
        # Connect to your postgres DB
        conn = psycopg2.connect("host=localhost dbname=postgres user=postgres password=123456")
        print('connnect')
        # Open a cursor to perform database operations
        cur = conn.cursor()        
        # Execute a query
        cur.execute('SELECT version()')
        # Print Result
        db_version = cur.fetchone()
        print(db_version)       
     # close the communication with the PostgreSQL
        cur.close()
    except (Exception) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
            print('Database connection closed.')

if __name__ == '__main__':
    connect()

执行后输出所连pg库的版本号

connnect
('PostgreSQL 9.6.16, compiled by Visual C++ build 1800, 64-bit',)
Database connection closed.

可见已经正常。具体细节怎么码参照文档https://www.psycopg.org/docs/

原文链接 https://www.jianshu.com/p/0ec2a5c9f1af

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。