【问题标题】:Python, Pandas, sql, read specific columns from a database with a for-loopPython,Pandas,sql,使用 for 循环从数据库中读取特定列
【发布时间】:2021-06-06 13:17:00
【问题描述】:

我的目标是使用 pd.read_sql 仅读取某些列名

## FILTER VALUES ##
#filtering all columns with temperature
filter_temp_values = df_column[df_column[0].str.contains("temperature")]
#filtering all columns with humidity
filter_humi_values = df_column[df_column[0].str.contains("humidity")]

result = cursor.fetchall()
for x in filter_temp_values[0]:
    #y = tuple(list(x))
    y = "SELECT '%s' FROM Raummonitoring" %(x)
    test = cursor.execute(y)

结果:

内部错误:找到未读结果

我也试过了:

result = cursor.fetchall()
for x in filter_temp_values[0]:
    y = tuple(list(x))
    z = f"SELECT ${y} FROM Raummonitoring"
    test = pd.read_sql(z, con = engine)

结果:

ProgrammingError: (mysql.connector.errors.ProgrammingError) 1370 (42000): 执行命令拒绝用户 'xxxx'@'%' 用于例程 'xxxx.$' [SQL: SELECT $('t', 'e', 'm', 'p', 'e', 'r', 'a', 't', 'u', 'r', 'e', ''、'e'、'r'、's'、''、'l'、'i'、't'、'e'、''、'3' , '', 'w', 'e', 'r', 'm', 's', 'e', 'r', '', '0', ''、'e'、'l'、's'、'y'、's'、'_'、'0')来自 Raummonitoring] (此错误的背景:http://sqlalche.me/e/14/f405

我的错是什么?

【问题讨论】:

    标签: python mysql pandas database database-cursor


    【解决方案1】:

    您可能会遇到将字符串列名转换为其字符元组的问题。

    如果您首先使用“,”加入连接列表,然后只向您的数据库提交 1 次,这样的操作是否有效?

    column_names = ['temperature_1', 'temperature_2', 'temperature_3']
    y = ', '.join(column_names)
    z = f"SELECT {y} FROM Raummonitoring"
        
    print(z)
    

    从 Raummonitoring 中选择温度_1、温度_2、温度_3

    【讨论】:

    • 你的帮助!我回答了它,并用你的小费 f"{}"
    猜你喜欢
    • 1970-01-01
    • 2019-11-28
    • 2023-03-26
    • 2018-07-16
    • 2021-05-26
    • 2016-10-11
    • 2021-03-15
    • 2020-07-19
    • 1970-01-01
    相关资源
    最近更新 更多