python—如何在select语句中使用在select语句外部定义的变量

wkftcu5l  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(343)

我想使用select语句将前525600行与数据集隔离开来,这非常容易使用limit语句,但是我想对58个单独的表进行隔离。我有一个表名列表,并试图定义一个函数来遍历所有表,但是我在函数中定义的变量名在sql语句中无法识别。这是我的密码:

import pandas as pd
from sqlalchemy import create_engine
import psycopg2

mylist = ['egauge13830','egauge13836','egauge13974','egauge14018','egauge14795','egauge15601',
          'egauge15623','egauge16133','egauge16608','egauge16616','egauge17073','egauge17311',
          'egauge18158','egauge18350','egauge18544','egauge19696','egauge19810','egauge19821',
          'egauge20358','egauge20407','egauge20670','egauge20925','egauge21932','egauge22084',
          'egauge22271','egauge22785','egauge23534','egauge24121','egauge24318','egauge2474',
          'egauge26086','egauge26944','egauge27467','egauge28351','egauge28489','egauge2850',
          'egauge2852','egauge28684','egauge30039','egauge30378','egauge3166','egauge3167',
          'egauge3171','egauge32290','egauge32507','egauge33764','egauge3608','egauge3611',
          'egauge4183','egauge5198','egauge6437','egauge7692','egauge7729','egauge7731',
          'egauge8253','egauge8617','egauge8816','egauge9102']

def first_chunk(egauge):
    engine = create_engine('postgresql://postgres:postgres@stargate/profiles')
    start_time_stmnt = """
    SELECT *
    FROM egauge
    LIMIT 525600
    """
    first = pd.read_sql_query(start_time_stmnt, engine)

def iterthro(data):
    for x in data:
        first_chunk(x)

iterthro(mylist)

我收到的错误告诉我“egauge”关系不存在。顺便说一句,我知道这段代码是非常无用的,因为它不做任何与选定的行,但我计划做更多与此,并希望找出这个问题之前,我继续。我尝试过一些简单的事情,比如不同的语录组合,我不确定我是犯了一个简单的语法错误,还是我的逻辑完全有缺陷。谢谢你的帮助!

zdwk9cvp

zdwk9cvp1#

这里,egauge是一个变量。所以你可以用 "{}".format(x) 在字符串中使用变量。希望有帮助!

def first_chunk(egauge):
    engine = create_engine('postgresql://postgres:postgres@stargate/profiles')
    start_time_stmnt = """
    SELECT *
    FROM {}
    LIMIT 525600
    """.format(egauge)
    first = pd.read_sql_query(start_time_stmnt, engine)
xa9qqrwz

xa9qqrwz2#

这有用吗?我没有一个例子来测试它,但我认为您需要更好地将语法和变量分开。

def first_chunk(egauge):
    engine = create_engine('postgresql://postgres:postgres@stargate/profiles')
    start_time_stmnt = " SELECT * " \
                       " FROM " + egauge + \
                       " LIMIT 525600 "
    first = pd.read_sql_query(sql=start_time_stmnt, con=engine, params=())

相关问题