从 SQL 查询方法返回泛型类型

问题描述 投票:0回答:1

我正在尝试从 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;
    }

接下来我可以尝试什么?

java sql generics resultset
1个回答
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

的进一步参考
© www.soinside.com 2019 - 2024. All rights reserved.