【发布时间】:2016-06-29 18:29:00
【问题描述】:
我正在考虑该方法的设计,使用户能够潜在地传递整数列表,指示用户希望从数据库中检索的列。
我不想硬编码本质上做同样事情的多个方法,即向用户显示来自同一个表的不同列。
这是 Oracle 教程中关于使用 JDBC 检索值的代码:
public static void viewTable(Connection con, String dbName)
throws SQLException {
Statement stmt = null;
String query =
"select COF_NAME, SUP_ID, PRICE, " +
"SALES, TOTAL " +
"from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID +
"\t" + price + "\t" + sales +
"\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
所以查询没有问题,列名可以串联起来,这取决于用户想看哪些列。问题出在 try 块中。如何从结果集中获得正确的格式?或者我应该简单地为每一列使用字符串?或者我应该对所有表列进行硬编码(rs.get 取决于列是什么数据类型),然后在 println 中只返回用户希望看到的列(实际上我该怎么做)?好吧,我想你明白我的问题了。
【问题讨论】:
-
简单的方法是,您可以将参数设置为列的数组和所有结果的getString
-
使用第二个循环遍历列,
getString应该可以完成这项工作,因为您只需要将其显示到控制台。
标签: java sql-server oracle jdbc