2009-01-14 46 views
1

我正在使用oracle數據庫和Jython。Jython,動態查詢多列

我可以從數據庫中獲取數據沒有問題。

results = statement.executeQuery("select %s from %s where column_id = '%s'", % (column, table, id)) 

這工作正常,如果我想拉一列數據。

說我想扔圈像這樣的列表:

columns = ['column1', 'column2', 'column3', 'column4', 'column5'] 

所以查詢結束這樣看:

results = statement.executeQuery("select %s, %s, %s, %s, %s from %s where column_id = '%s'", % (column1, column2, column3, column4, column5, table, id)) 

我怎麼能這樣做呢?

我想實現這一目標的原因是因爲我可能想要拉6或7列,我想將不同的查詢存儲在外部文件中。

我希望你明白我的意思。如果沒有,我會盡我所能地儘可能地重新說出它。

乾杯

亞瑟

回答

3

你可以簡單地所有列替換到您的查詢作爲一個字符串,像這樣:

columns = ['column1', 'column2', 'column3', 'column4', 'column5'] 
results = statement.executeQuery("select %s from %s where column_id = '%s'" % (",".join(columns), table, id)) 

順便說一句,這不是保護免受SQL注射,所以我假設列,表和ID輸入是程序生成或消毒。

+0

乾杯,偉大的工程! – RailsSon 2009-01-14 15:28:00