【发布时间】:2020-03-05 10:21:34
【问题描述】:
我只想指定表名,它会自动将其所有数据转换为 JSON 格式
我已尝试使用 JDBC 将表中的数据存储到 JSON 中的代码。
public class DataBaseToJson {
public static ResultSet RetrieveData() throws Exception {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost/studentsDB?autoReconnect=true&useSSL=false";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "root");
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery("Select * from students");
return resultSet;
}
public static void main(String args[]) throws Exception {
JSONObject jsonObject = new JSONObject();
JSONArray array = new JSONArray();
ResultSet resultSet = RetrieveData();
while (resultSet.next()) {
JSONObject record = new JSONObject();
record.put("students ID", resultSet.getInt("students_id"));
record.put("students Name", resultSet.getString("students_name"));
array.add(record);
}
jsonObject.put("students Information", array);
try {
FileWriter file = new FileWriter("output.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我不想在文件中指定文件。我想让它通用,这样我们就可以只输入表名,它会自动转换该表中的所有数据并保存到 JSON 文件中。
【问题讨论】: