gpt4 book ai didi

java - 如何将从数据库获取的值存储到文本文件中

转载 作者:太空宇宙 更新时间:2023-11-04 13:20:46 25 4
gpt4 key购买 nike

我需要您的帮助将从数据库中获取的值存储到文本文件 (Sample.txt) 中。每个获取的行都应存储在文本文件中,并用换行符分隔。每个检索到的列之后应该用行“|”分隔,所以我需要你的帮助。这是代码:

public void GenerateTXT() {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();

String sql = "SELECT id, name, amount FROM Employee";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getString("name");
String first = rs.getInt("amount");
}
rs.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}

最佳答案

您可以使用以下代码。

public void GenerateTXT() { 
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();

File file = new File("/path/to/file/filename.txt");

// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);

String sql = "SELECT id, name, amount FROM Employee";
ResultSet rs = stmt.executeQuery(sql);

while(rs.next()){
int id = rs.getInt("id");
int age = rs.getString("name");
String first = rs.getInt("amount");
bw.append(id+"|"+age+"|"+first+"\n");
}
rs.close();
bw.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}

关于java - 如何将从数据库获取的值存储到文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33087233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com