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

时间:2017-07-18 22:00:31

标签: python pandas sqlalchemy

我创建了一个脚本来从db中提取数据并输出到管道文本文件。但是,现在我想让用户提供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')

ID会是一个查询列表,如(' id1',id2',' id3')

2 个答案:

答案 0 :(得分:0)

参数的语法因您的数据库而异,但您的SQL需要看起来像这样。

SQL

ids=input(SELECT * FROM table WHERE data IN (:ids))


   -- without knowing your DB this is psuedo code.  
   -- In postgres you might be able to use ANY(ARRAY) and use native postgres any python arrays

python代码类似于

data1 = pandas.read_sql_query(
                            sa.text(ids),
                            con=conn,
                            params={ 
                                'ids'  : [1,2,3,4,5]
                            }
                      )

...也 read_sql返回一个数据帧

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


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

http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_sql.html

答案 1 :(得分:0)

我已经解决了一半的问题,这里是代码,但遇到问题,如果我为输入提供多个值,它不会返回结果,给出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()

有人可以帮忙吗?