使用psycopg2连接在线数据库PostgreSQL数据库。
(1) 安装psycopg2
打开命令提示符或PowerShell,并输入以下命令来安装psycopg2-binary:
pip install psycopg2-binary
(2) 连接代码示例,
import psycopg2
import time
start_t = time.time()
# 连接到远程PostgreSQL数据库
conn = psycopg2.connect(
host = "10.XXX.153.150", #IP地址
port = "2023", #端口号
database = "ims_HEE_XXX-34465-0420", #数据库名
user = "yonghuming", #用户名
password = "mima" #密码
)
cursor = conn.cursor()
sqlstr = "select id, length, pkid from bd_cha where 100.0 < length and length < 110.0 limit 3;"
cursor.execute(sqlstr)
for row in cursor:
id = int(row[0])
length = float(row[1])
pkid = int(row[2])
print(f'id = {id}, length = {length}, pkid = {pkid}!')
conn.commit()
cursor.close()
conn.close()
end_t = time.time()
print(f'程序成功执行,耗时{(end_t - start_t) / 60.0}分钟!')