2016-02-21 97 views
0

我試圖從SQL查詢方法返回通用的類型,但我堅持從數據庫到泛型類型分配值:返回泛型類型從SQL查詢方法

public static <T extends Comparable<T>> T selectQuery(Connection conn, String sql, T[] parameters) { 
     T value = null; 
     try { 
      PreparedStatement ps = conn.prepareStatement(sql); 
      List<T> list = Arrays.asList(parameters); 
      for (T param : list) { 
       if (param instanceof String) { 
        ps.setString(list.indexOf(param), (String) param); 
       } else if (param instanceof Integer) { 
        ps.setInt(list.indexOf(param), (Integer) param); 
       } else if (param instanceof Double) { 
        ps.setDouble(list.indexOf(param), (Double) param); 
       } 
      } 
      ResultSet rs = ps.executeQuery(); 
      while (rs.next()) { 
       //AM STUCK RIGHT HERE************ 
      } 
      Conn.closeConn(conn); 
     } catch (Exception asd) { 
      System.out.println(asd.getMessage()); 
     } 
     return value; 
    } 

請幫我的建議迎接這一挑戰。

+0

該數據庫還引用包含字符串,整數,雙等..? –

回答

1
int i=0; 
while (rs.next()) 
{ 
    int type=rs.getMetaData().getColumnTypeName(i); 
    if(type ==Types.INTEGER) 
     value = (T) rs.getInt(); 
    else if(type ==Types.DOUBLE) 
     value = (T) rs.getDouble(); 
    else if(type ==Types.FLOAT) 
     value = (T) rs.getFloat(); 
    else if(type ==Types.VARCHAR) 
     value = (T) rs.getString(); 
    else if(type ==Types.LONG) 
     value = (T) rs.getLong(); 
} 

有關Types in sql