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/