使用psycopg2连接在线数据库PostgreSQL数据库。
(1) 安装psycopg2
打开命令提示符或PowerShell,并输入以下命令来安装psycopg2-binary:文章来源:https://www.toymoban.com/news/detail-514264.html
pip install psycopg2-binary
(2) 连接代码示例,文章来源地址https://www.toymoban.com/news/detail-514264.html
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}分钟!')
到了这里,关于python3连接pg库做SQL查询的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!