java查询出来的SQL数据导出多个txt
时间: 2024-03-19 11:45:18 浏览: 21
你可以使用Java的文件操作API和JDBC API来实现查询出来的SQL数据导出多个txt文件。具体步骤如下:
1. 连接数据库,执行SQL查询语句,获取查询结果;
2. 循环遍历查询结果,每次遍历都需要执行以下操作:
a. 获取需要导出的数据,例如:String data = resultSet.getString("column_name");
b. 创建一个文件对象,指定文件路径和文件名,例如:File file = new File("C:\\temp\\file" + i + ".txt");
c. 创建一个文件输出流对象,将数据写入文件中,例如:FileOutputStream fos = new FileOutputStream(file);
d. 将需要写入的数据转换为字节数组,例如:byte[] bytes = data.getBytes();
e. 将字节数组写入文件中,例如:fos.write(bytes);
f. 关闭文件输出流,释放资源,例如:fos.close();
3. 循环结束后,所有txt文件都已经导出成功。
以下是示例代码:
```
public class ExportTxt {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM table_name";
try {
// 连接数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 执行SQL查询语句
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
int i = 0;
while(rs.next()) {
// 获取需要导出的数据
String data = rs.getString("column_name");
// 创建文件对象
File file = new File("C:\\temp\\file" + i + ".txt");
// 创建文件输出流对象
FileOutputStream fos = new FileOutputStream(file);
// 将数据转换为字节数组
byte[] bytes = data.getBytes();
// 将字节数组写入文件中
fos.write(bytes);
// 关闭文件输出流,释放资源
fos.close();
i++;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接和资源
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
当然,你需要根据实际需求,修改文件路径、文件名、SQL查询语句、查询结果的获取方式等参数。