用java编写代码,将student数据表中所有数据保存在study文件夹中。如果数据表不存在或者没有数据则报错
时间: 2023-02-24 18:15:13 浏览: 151
以下是用 Java 编写的代码示例:
```
import java.io.*;
import java.sql.*;
public class SaveData {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
FileOutputStream fos = null;
try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 创建 statement
stmt = conn.createStatement();
// 执行查询
rs = stmt.executeQuery("SELECT * FROM student");
// 如果没有数据,抛出异常
if (!rs.next()) {
throw new SQLException("student 数据表中没有数据");
}
// 创建 study 文件夹
File studyFolder = new File("study");
if (!studyFolder.exists() && !studyFolder.mkdir()) {
throw new IOException("创建 study 文件夹失败");
}
// 保存数据
do {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String data = String.format("id: %d, name: %s, age: %d\n", id, name, age);
fos = new FileOutputStream(new File(studyFolder, id + ".txt"));
fos.write(data.getBytes());
} while (rs.next());
} catch (ClassNotFoundException | SQLException | IOException e) {
e.printStackTrace();
} finally {
// 关闭连接和资源
try {
if (fos != null) fos.close();
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
}
```
该代码中,首先使用 `Class.forName` 加载驱动,然后使用 `DriverManager.getConnection` 获取数据库连接,接着创建 `Statement` 并执行查询,如果