我想将结果集转换为字符串。之后,我将使用该字符串编写一个html文件。Course是一个表,包含courseid(String),name(String),先决条件(String)连接数据库就可以了。这是我的代码和想法。您能评估我的想法或给我一些更好的解决方案吗?
private static void printRecordFromCourse() throws SQLException {
Connection dbConnection = null;
Statement stmt = null;
String printSQL = "SELECT * FROM course";
try {
dbConnection = getDBConnection();
stmt = dbConnection.createStatement();
ResultSet rs=stmt.executeQuery(printSQL);
while(rs.next()){
//Retrieve by column name
String courseid = rs.getString("courseid");
String name = rs.getString("name");
String prerequisites = rs.getString("prerequisites");
String result+ = "<tr><td>"+courseid+"</td><td>"+name+"</td><td>"+prerequisites"</td></tr>";
}
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stmt != null) {
dbConnection.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 ArrayList 并将列存储在其中,例如:
List allRows = new ArrayList();
while(rs.next()){
String[] currentRow = new String[numberColumns];
for(int i = 1;i<=numberColumns;i++){
row[i-1]=rs.getString(i);
}
rows.add(row);
}
Run Code Online (Sandbox Code Playgroud)
您的 ArrayList 现在包含字符串数组,其中每个数组代表一行。现在您可以简单地将字符串数组条目转换为字符串,例如使用Arrays.toString(allRows.get(i));
| 归档时间: |
|
| 查看次数: |
42435 次 |
| 最近记录: |