2009-10-03 75 views
2

假設我有一張有3列的表格:C1,C2,C3PreparedStatement:我可以提供列名作爲參數嗎?

我根據C1列進行搜索。 我可以做類似這樣的東西(這是行不通的 - 因爲這是不prepareStatement它的使用 :)的方式)

String c;// the name of the column 

...  
String sql = "select * from table where ? = ?"; 
       pre = con.prepareStatement(sql); 
       pre.setString(1, c); 
       pre.setString(1, i); 
       rs = pre.executeQuery(); 

主要的想法,我不希望有每列有3個ifs。優雅的解決方案?

+0

不應該是..... pre.setString(1,'c1'); pre.setString(2,i); – 2009-10-03 22:15:47

+0

我做了更正。 :) – 2009-10-03 22:19:14

回答

2

你可以編寫了一組SQL查詢,並將它們存儲在一張地圖,然後抓住基於所涉及的專欄之一。

enum column { a, b, c} 

Map<column, string> str; 

static { 
str.put(a, "select * from tbl where a = ? "); 
... 
} 

然後根據枚舉稍後抓取一張地圖。在sql語句中附加字符串有一種成爲未來安全問題的方式。

0

你不能做到這一點:

String c;// the name of the column 

...  
String sql = "select * from table where " + c + " = ?"; 
       pre = con.prepareStatement(sql); 
       pre.setString(1, i); 
       rs = pre.executeQuery(); 

如果沒有,那麼這可能是一個解決方案:

String c;// the name of the column 

...  
String sql = "select * from table where ('C1' = ? AND C1 = ?) 
            OR ('C2' = ? AND C2 = ?) 
            OR ('C3' = ? AND C3 = ?)" 
       pre = con.prepareStatement(sql); 
       pre.setString(1, c); 
       pre.setString(2, i); 
       pre.setString(3, c); 
       pre.setString(4, i); 
       pre.setString(5, c); 
       pre.setString(6, i); 
       rs = pre.executeQuery(); 
+0

我知道。我在問題中寫道。 :) – 2009-10-03 22:28:25

+0

沒有看到更新;我刪除了關於將Col名稱傳遞給PreparedStatement的部分。 – manji 2009-10-03 23:12:01

3

這是行不通的。準備語句解析SQL,發送到數據庫進行驗證和編譯。如果問號可以代替SQL的某些部分,那麼您將失去整個綁定變量 - 速度和安全性。您將重新引入SQL注入,並且必須重新編譯所有參數的語句。

不會像SELECT * FROM table WHERE c1 = ? OR c2 = ? OR c3 = ?這樣的東西更好(當然取決於索引和表大小)。

0

使用動態查詢和java.sql.Statement

String whereClause = c + " = " + i; 

// Form the dynamic Query 
StringBuffer query = new StringBuffer("SELECT * FROM TABLE"); 
// Add WHERE clause if any 
query.append(" WHERE " + whereClause); 

// Create a SQL statement context to execute the Query 
Statement stmt = con.createStatement(); 

// Execute the formed query and obtain the ResultSet 
ResultSet resultSet = stmt.executeQuery(query.toString()); 
+1

只是要小心,因爲它可以導致sql注入 – 2009-10-03 23:14:44

相關問題