------解决方案--------------------------------------------------------
public List query(String sql) {
Vector content = new Vector();
Connection conn = null;
Statement stmt = null;
try {
logger.debug("查询语句:"+sql);
//System.out.println("查询语句:"+sql);
conn = this.getConnection();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsMeta = rs.getMetaData();
while (rs.next()) {
int columnNum = rsMeta.getColumnCount();
String[] field = new String[columnNum];
String fieldValue = null;
for (int i = 1; i <= columnNum; i++) {
//fieldValue = rs.getString(rsMeta.getColumnName(i));
fieldValue = rs.getString(i);
if (fieldValue == null) {
fieldValue = "";
}
field[i - 1] = fieldValue;
}
content.add(field);
}
} catch ( SQLException e) {
logger.error(e.toString());
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
this.closeConnection(conn);
} catch (SQLException e1) {
logger.error(e1.toString());
e1.printStackTrace();
}
}
return content;
}
public List query(String sql) {
Vector content = new Vector();
Connection conn = null;
Statement stmt = null;
try {
logger.debug("查询语句:"+sql);
//System.out.println("查询语句:"+sql);
conn = this.getConnection();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsMeta = rs.getMetaData();
while (rs.next()) {
int columnNum = rsMeta.getColumnCount();
String[] field = new String[columnNum];
String fieldValue = null;
for (int i = 1; i <= columnNum; i++) {
//fieldValue = rs.getString(rsMeta.getColumnName(i));
fieldValue = rs.getString(i);
if (fieldValue == null) {
fieldValue = "";
}
field[i - 1] = fieldValue;
}
content.add(field);
}
} catch ( SQLException e) {
logger.error(e.toString());
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
this.closeConnection(conn);
} catch (SQLException e1) {
logger.error(e1.toString());
e1.printStackTrace();
}
}
return content;
}
本文介绍了一个使用Java进行数据库SQL查询的方法。通过创建Connection和Statement对象,执行SQL查询,并利用ResultSet获取查询结果。同时,该文展示了如何处理查询过程中的异常,并确保资源得到妥善关闭。
1912

被折叠的 条评论
为什么被折叠?



