从MySQL数据库中导出数据
package lianjie;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* java读取数据库内容并存放到文件中
*
* @author wang
*
*/
public class JavaToSQLTest {
static int count;
public static void main(String[] args) {
PrintWriter pw = null;
FileWriter fw = null;
Connection conn = null;
Statement st=null;
String guanjian;
try {
conn = Dbutil.getConnection();
st=conn.createStatement();
// 创建预编译SQL对象
PreparedStatement ps = conn
.prepareStatement("select guanjian from keyword");
// 执行SQL,获取结果集rs
ResultSet rs = ps.executeQuery();
// 处理结果集
while (rs.next()) {
guanjian = rs.getString("guanjian");
String filename = "aa" + ".txt";
// 关联文件
File file = new File(filename);
if(!file.exists()){
// 判断文件不存在就new新文件,写数据
try {
file.createNewFile();
// java IO流和文件关联
pw = new PrintWriter(file);
pw.print(guanjian);
pw.println();
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
// 判断文件存在,就以FileWriter文件追加的方式写文件
try {
fw = new FileWriter(filename,true);
System.out.println();
fw.write("\n"+guanjian);
fw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("数据库连接错误");
System.exit(1);
} finally {
if (conn != null) {
try {
// 关闭数据库连接
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (pw != null) {
// 关闭IO流
pw.close();
}
if(fw != null){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}