2017-07-18 42 views
0

我已经创建了一个脚本来从db中提取数据并输出到管道文本文件。不过,现在我想拥有用户提供的ID,然后使用用户输入的查询中的像Python,Pandas,Sqlalchemy:在查询中使用input()中的值

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’ )

+0

您不需要再次将data1作为数据帧。它是来自read_sql的数据框。 – Kosch

+0

好的,纠正了删除冗余 - 如何回答实际紧迫的问题:) – PeaceTree

+0

您使用的数据库是什么?这是你问题中最重要的部分。 – Kosch

回答

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

+0

@ Kosch - 对不起,我以为我把它放在那里 - 我使用cx_Oracle连接到Oracle数据库引擎,如engine1 = create_engine(“oracle + cx_oracle:............. – PeaceTree

+0

另外,我不知道用户会给出多少个ID值 - 可能是1或5或100等。 – PeaceTree

0

我已经解决了这里一半的问题是代码,但运行到以下问题:如果我给输入多个值,它不返回的结果,让1号工作在这个代码

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() 

谁能帮忙?

+0

随着您继续朝着解决方案迈进,请通过更新和说明来编辑原始问题,以便贡献者可以找到最近的问题 –

相关问题