我有這個功能,需要使它成爲一個功能。唯一的區別是輸入變量類型sourceColumnValue。此變量可以是字符串或整數但函數的返回值必須始終爲整數。 我知道我需要使用泛型但不能這樣做。在函數中使用泛型的問題
public Integer selectReturnInt(String tableName, String sourceColumnName, String sourceColumnValue, String targetColumnName) {
Integer returned = null;
String query = "SELECT "+targetColumnName+" FROM "+tableName+" WHERE "+sourceColumnName+"='"+sourceColumnValue+"' LIMIT 1";
try {
Connection connection = ConnectionManager.getInstance().open();
java.sql.Statement statement = connection.createStatement();
statement.execute(query.toString());
ResultSet rs = statement.getResultSet();
while(rs.next()){
returned = rs.getInt(targetColumnName);
}
rs.close();
statement.close();
ConnectionManager.getInstance().close(connection);
} catch (SQLException e) {
System.out.println("Заявката не може да бъде изпълнена!");
System.out.println(e);
}
return returned;
}
// SELECT (RETURN INTEGER)
public Integer selectIntReturnInt(String tableName, String sourceColumnName, Integer sourceColumnValue, String targetColumnName) {
Integer returned = null;
String query = "SELECT "+targetColumnName+" FROM "+tableName+" WHERE "+sourceColumnName+"='"+sourceColumnValue+"' LIMIT 1";
try {
Connection connection = ConnectionManager.getInstance().open();
java.sql.Statement statement = connection.createStatement();
statement.execute(query.toString());
ResultSet rs = statement.getResultSet();
while(rs.next()){
returned = rs.getInt(targetColumnName);
}
rs.close();
statement.close();
ConnectionManager.getInstance().close(connection);
} catch (SQLException e) {
System.out.println("Заявката не може да бъде изпълнена!");
System.out.println(e);
}
return returned;
}
看起來有些沮喪的精神病患者來和下投票大家([MEE太(http://stackoverflow.com/questions/5133958/problem-using-generics-in-function/5133995#5133995)): d – 2011-02-27 15:53:22
切勿使用字符串連接的SQL,這是一個安全風險,反模式:http://www.ibm.com/developerworks/java/library/j-typesafejpa/也釋放宣稱資源,而不是最終的,他們嘗試塊(否則失敗將不會釋放聲稱的資源!)。 – Kdeveloper 2011-02-27 16:29:28