使用jdbc作为List获取整行

时间:2014-01-09 15:23:05

标签: java sql excel jdbc

我需要从多个表中获取数据并导出到每个表的excel表中。我不想使用getXXX()方法,因为有大量列,我不知道每列的数据类型。我需要获取整行并将结果存储在List中。 我使用getObject()获取了每个列,并使用MetaData.getColumnClassName()获取了类类型。

例如

Object val = resultSet.getObject(i);

我尝试使用getColumnClassName()将此val转换为其实际类型,但在投射时会出现错误。

任何人都可以帮助我。

public class Row {

public Map<Object, Class> row;
public static Map<String, Class> TYPE;

static {
    TYPE = new HashMap<String, Class>();
    TYPE.put("INTEGER", Integer.class);
    TYPE.put("NUMERIC", BigDecimal.class);
    TYPE.put("DOUBLE", Double.class);
    TYPE.put("VARCHAR2", String.class);

}

public Row() {
    row = new HashMap<Object, Class>();
}

public <t> void add(t data) {
    row.put(data, data.getClass());
}

public void add(Object data, String sqlType) {
    add((Row.TYPE.get(sqlType)) data);
}

public static void formTable(ResultSet rs, List<Row> table) throws SQLException {
    if(rs == null)
        return;
    ResultSetMetaData rsmd = rs.getMetaData();
    int colCt = rsmd.getColumnCount();
    while(rs.next()) {
        Row row = new Row();
        for(int i = 0; i < colCt; i++) {
            row.add(rs.getObject(i), rsmd.getColumnTypeName(i));
        }
        table.add(row);
    }
}
public static void main(String[] args) {

}

}

3 个答案:

答案 0 :(得分:1)

试试这段代码:

Connection connection = DriverManager.getConnection("URL", "USERNAME", "PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from table");
ResultSet resultSet = statement.executeQuery();

if (resultSet != null) {
    while (resultSet.next()) {
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {

            int type = resultSetMetaData.getColumnType(i);
            if (type == Types.VARCHAR || type == Types.CHAR) {
                 System.out.println(resultSet.getString(i));
            } else {
                 System.out.println(resultSet.getLong(i));
            }
        }

         System.out.println("-----------");
    }
}

您应该使用其他数据类型扩展它。

答案 1 :(得分:0)

第1步:获取元数据

ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
int[] columnsType = new int[numColumns + 1];
columnsType[0] = 0;
for (int i = 1; i <= numColumns; i++) 
    columnsType[i] = rsmd.getColumnType(i);

第2步:从结果集中一次获取一行并检查数据类型

String s;
Object o;
while (rs.next()) {
    for (int i = 1; i <= numColumns; i++) {
        if (columnsType[i] == java.sql.Types.NUMERIC || columnsType[i] == java.sql.Types.CHAR || columnsType[i] == java.sql.Types.VARCHAR) {
            s = rs.getString(i);
        } else if (columnsType[i] == java.sql.Types.NVARCHAR) {
            s = rs.getNString(i);
        } else if (columnsType[i] == java.sql.Types.BOOLEAN) {
            // TODO
        } else if (columnsType[i] == java.sql.Types.FLOAT || columnsType[i] == java.sql.Types.DOUBLE) {
            // TODO
        } else if (columnsType[i] == java.sql.Types.TINYINT || columnsType[i] == java.sql.Types.SMALLINT || columnsType[i] == java.sql.Types.INTEGER || columnsType[i] == java.sql.Types.BIGINT) {
            // TODO
        } else if (columnsType[i] == java.sql.Types.DATE || columnsType[i] == java.sql.Types.TIMESTAMP) {
            // TODO
        } else {
            o = rs.getObject(i);
        }
    }
}

第3步:填充空白并添加异常处理

第4步:写入Excel(循环内部)

答案 2 :(得分:0)

public class EXECUTEQUERY implements Module {

    private static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String userId;
    String result = "";
    String resp = "";
    static int count = 1;
    private final Logger log = Logger.getLogger("EXECUTEQUERY");

    private void dbg(String msg) {
        log.info(userId + ":" + msg);
    }
    private void dbg(Exception ex) {
        log.info(ex.getMessage());
        ex.printStackTrace();
    }
    private void uDbg(String msg) {
        log.info(userId + " :" + msg);
    }
    private void uDbg(Exception ex) {
        uDbg(ex.getMessage());
        ex.printStackTrace();
    }
    public String main(UserContext userContext, String reqXml) {
        dbg("Query recieved is " + reqXml);

        String resp;
        userId = userContext.getUserId();

        if (userContext.getAction().equals("EXECUTEQUERY")) {
            if (reqXml == null || reqXml.equals("")) {
                result = "!Please Enter the query";
            } else {
                result = getQueryResult(userContext, reqXml);
            }
        }
        return result;
    }
    /***
     * 
     * for adding search record in backend created by @shyamlal yadav
     * @param userContext
     * @param reqXml 
     */
    public void addQueryLog(UserContext userContext, String reqXml) {
         dbg("inside addQueryLog methos request is " + reqXml);
        userId = userContext.getUserId();

        dbg( userId +"this user is selecting value from screen");

        System.out.println("recieve request  is " + reqXml);
        PreparedStatement pStmt = null;
        Connection eodConn = null;
        dbg("addQueryLog recieved for log  " + reqXml);

        Date date = new Date();
        java.sql.Date sqlDate = new java.sql.Date( date.getTime()); 
        eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();

        try {
            pStmt = eodConn.prepareStatement("insert into EOD_QRY_EXEC_LOG (QRY_EXEC_TIMESTAMP, QRY_TEXT,OPERATOR_ID)\n"
                    + " values (?,?,?)");
            pStmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
            pStmt.setString(2, reqXml);
            pStmt.setString(3, userId);
            pStmt.executeQuery();
        } catch (SQLException ex)  {
            dbg("Exception is " + ex);
            return;
        }
        EODConnectionFactory.returnFCConnectionToPool(eodConn);
        return;
    }

    /*
     This method returns query excecuted table data with separators.
     @Shaymlal, 
     */
    public String getQueryResult(UserContext userContext, String reqXml) {
        String field_value = "";
        String lsitofquery = "";
        String resultlist = "";
        dbg("Inside getQueryResult method");
        Connection eodConn = null;
        Statement stmt = null;
        eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
        try {
            stmt = eodConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            ResultSet rs = stmt.executeQuery(reqXml);
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            dbg("Total no of column is:" + columnCount);

            int rsCount = 1;
            while (rs.next()) {
                if (rsCount == 1) {
                    for (int i = 1; i <= columnCount; i++) {
                        resultlist += "~" + rsmd.getColumnName(i);
                    }
                }
                for (int i = 1; i <= columnCount; i++) {
                    field_value += "~" + rs.getString(i);
                }
                field_value = field_value + "~<>";
                lsitofquery = resultlist + "~>" + field_value;
                rsCount = rsCount + 1;
            }
        } catch (Exception ex) {
            dbg("Exception is " + ex);
            return "!Exception  invalid query: " + ex;
        }
        EODConnectionFactory.returnFCConnectionToPool(eodConn);

        // return rowCount > 0 ? lsitofquery+">" : "!Table is Empty" ;
        addQueryLog(userContext,reqXml);
        return lsitofquery + ">";
    }
}