Java写一段查数据库导出表格的代码
时间: 2023-03-14 19:12:04 浏览: 55
String url = "jdbc:mysql://localhost:3306/test";
String username = "username";
String password = "password";try {
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
String sql = "select * from table";
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
String[] colName = new String[colCount];
for(int i=0; i<colCount; i++) {
colName[i] = rsmd.getColumnName(i+1);
}
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
while(rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for(int i=0; i<colCount; i++) {
map.put(colName[i], rs.getObject(i+1));
}
list.add(map);
}
ExportExcel.exportExcel(list, "表格名称");
rs.close();
stmt.close();
conn.close();
} catch(Exception e) {
e.printStackTrace();
}答:try {
String url = "jdbc:mysql://localhost:3306/test";
String username = "username";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
String sql = "select * from table";
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
String[] colName = new String[colCount];
for(int i=0; i<colCount; i++) {
colName[i] = rsmd.getColumnName(i+1);
}
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
while(rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for(int i=0; i<colCount; i++) {
map.put(colName[i], rs.getObject(i+1));
}
list.add(map);
}
ExportExcel.exportExcel(list, "表格名称");
rs.close();
stmt.close();
conn.close();
} catch(Exception e) {
e.printStackTrace();
}