Python、Pandas、Sqlalchemy:在查询中使用input()中的值

Python、Pandas、Sqlalchemy:在查询中使用input()中的值,python,pandas,sqlalchemy,Python,Pandas,Sqlalchemy,我创建了一个脚本,从数据库中提取数据并输出到管道文本文件。但是,现在我想让用户提供ID,然后在查询中使用用户输入,以进行类似的操作 engine1 = create_engine() ids=input("Enter the IDs needed for file generation: ") print("extracting the data for ", ids) stext=text("SELECT * FROM table WHERE data IN ids") data1 = pd.

我创建了一个脚本,从数据库中提取数据并输出到管道文本文件。但是,现在我想让用户提供ID,然后在查询中使用用户输入,以进行类似的操作

engine1 = create_engine()
ids=input("Enter the IDs needed for file generation: ")
print("extracting the data for ", ids)
stext=text("SELECT * FROM table WHERE data IN ids")
data1 = pd.read_sql(stext, con=engine1)
data1.to_csv('new.txt',sep='|',encoding='utf8',index=False,line_terminator='||\n')

ids将是一个类似于('id1',id2','id3')的查询列表。

参数语法将根据您的数据库而有所不同,但您的SQL需要类似于此

SQL

python代码类似于

data1 = pandas.read_sql_query(
                            sa.text(ids),
                            con=conn,
                            params={ 
                                'ids'  : [1,2,3,4,5]
                            }
                      )
……也 read\u sql返回一个数据帧

data1 = pd.read_sql(stext, con=engine1)


data1.to_csv('new.txt',sep='|',encoding='utf8',index=False,line_terminator='||\n')

我已经解决了一半的问题,这里的问题是代码,但遇到了一个问题,如果我为输入提供多个值,它不会返回结果,给出1个id在该代码中起作用

def extractPcFile():
pd.set_option('display.float_format', lambda x: '%.0f' % x)
dsn = "oracle+cx_oracle://)))"
engine = create_engine(dsn)
session = sessionmaker(bind=engine)
connection = engine.connect()
session = session(bind=connection)
metadata = MetaData()
Base = declarative_base()
hcids=input("Enter the HCIDs needed for PC file generation:")
print("extracting the data for ", hcids)
sql = ("select * from table where HCID in (:hcids)")
result=engine.execute(sql, hcids,).fetchall()
print(result)
extractPcFile()

有人能帮忙吗?

您不需要再次将data1设为数据帧。当它从read_sql中产生时,它是一个数据帧。好的,更正了这一点,以删除冗余-如何回答实际紧迫的问题:)您使用的是什么数据库?这是你问题中最重要的部分。@Kosch很抱歉,我以为我把它放进去了-我正在使用cx\u Oracle连接到Oracle exadata,比如engine1=create\u engine(“oracle+cx_oracle:……此外,我不知道用户会给出多少ID值——可能是1、5或100等。随着您在解决方案方面不断取得进展,请编辑原始问题并进行更新和澄清,以便贡献者可以找到最新的问题
def extractPcFile():
pd.set_option('display.float_format', lambda x: '%.0f' % x)
dsn = "oracle+cx_oracle://)))"
engine = create_engine(dsn)
session = sessionmaker(bind=engine)
connection = engine.connect()
session = session(bind=connection)
metadata = MetaData()
Base = declarative_base()
hcids=input("Enter the HCIDs needed for PC file generation:")
print("extracting the data for ", hcids)
sql = ("select * from table where HCID in (:hcids)")
result=engine.execute(sql, hcids,).fetchall()
print(result)
extractPcFile()