java连接数据库执行SQL并把查询到的数据保存到磁盘
时间:2021-07-01 10:21:17
帮助过:20人阅读
java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class TestDemo {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"
;
static final String DB_URL = "jdbc:mysql://10.7.164.107:3306/databaseName"
;
@Test
public void Test1()
throws ClassNotFoundException, SQLException, FileNotFoundException {
//设置查询到的数据存储地点
//设置数据库用户名密码
final String USER = "root"
;
final String PASS = "password"
;
Connection conn =
null;
Statement stmt =
null;
//设置查询到的数据存储地点
FileOutputStream fos =
new FileOutputStream(System.getProperty("user.dir")+"\\src\\topsec\\test.txt",
true);
PrintStream p =
new PrintStream(fos);
try {
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//连接数据库
System.out.println("连接数据库成功"
);
Class.forName(JDBC_DRIVER);//加载JDBC
stmt = conn.createStatement();
//创建Statement对象
String sql = ""
;
ResultSet rs = stmt.executeQuery(sql);
//创建数据对象
//遍历数据对象,把数据存到txt
while (rs.next()){
String taskId = rs.getString("taskId"
);
String processInstanceld = rs.getString("processInstanceId"
);
String order_id = rs.getString("order_id"
);
p.println(taskId+","+order_id+","+
processInstanceld);
}
p.close();
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=
null) stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=
null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("数据收集完成!"
);
}
}
java连接数据库执行SQL并把查询到的数据保存到磁盘
标签:ati row 完成 drive 数据保存 set com dir 数据库