msymsywhc 2022-11-04 13:41 采纳率: 100%
浏览 87
已结题

python查询数据库中一列数据并存放在一个列表中

问题遇到的现象和发生背景

python连接postgresql查询数据表中某一列数据,想把查询得到的数据存放在一个list中

用代码块功能插入代码,请勿粘贴截图
import glob
import psycopg2 as psy
import os

filepattern = r'E:\study\Python\argo\202206.tar\202206\202206\*_*.dat'
filelist = glob.glob(filepattern)

"""连接库"""
host = 'localhost'
port = 5432
dbname = 'postgres'
user = 'postgres'
password = '123'
conn = psy.connect(host=host, port=port, dbname=dbname, user=user, password=password)

cursor = conn.cursor()

sql = '''
SELECT pressure FROM tempsalt
WHERE platformnumber = %s
'''
cursor.execute(sql, [1901302])

print(cursor)
results=cursor.fetchall()
for items in results:
    pre=items[0]
    print(pre)

运行结果及报错内容

4.5
7.1
10.5
15.4
19.6
24.6
30.4
34.3
39.8
44.9
49.8
54.6
59.6
64.6
69.4
74.6
80.5
85.2
89.9
93.6
97.8
110.3
118.5
130.6
140.1
149.9
160.5
170.2
180.4
190.4
200.5
209.8
220.3
229.5
240.5
250.4
260.0
269.9
280.3
290.2
300.2
310.1
319.9
330.0
339.9
349.9
359.9
380.5
400.1
420.2
439.9
459.8
479.7
500.3
549.7
599.9
648.3
700.5
800.0
900.5
999.2
1099.6
1200.3
1298.0
1399.8
1497.4
1599.9
1700.5
1800.4
1900.3

进程已结束,退出代码0

我想要达到的结果

想达到这样的效果:[4.5,7.1,10.5,15.4,19.6,24.6,30.4,34.3,39.8]

  • 写回答

4条回答 默认 最新

  • 爱音斯坦牛 全栈领域优质创作者 2022-11-04 13:51
    关注

    这个简单,代码如下,有帮助的话采纳一下哦!

    import glob
    import psycopg2 as psy
    import os
    
    filepattern = r'E:\study\Python\argo\202206.tar\202206\202206\*_*.dat'
    filelist = glob.glob(filepattern)
    
    """连接库"""
    host = 'localhost'
    port = 5432
    dbname = 'postgres'
    user = 'postgres'
    password = '123'
    conn = psy.connect(host=host, port=port, dbname=dbname, user=user, password=password)
    
    cursor = conn.cursor()
    
    sql = '''
    SELECT pressure FROM tempsalt
    WHERE platformnumber = %s
    '''
    cursor.execute(sql, [1901302])
    
    print(cursor)
    results = cursor.fetchall()
    new_results = []
    for items in results:
        new_results.append(items[0])
    
    print(new_results)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 11月12日
  • 已采纳回答 11月4日
  • 创建了问题 11月4日

悬赏问题

  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题