zoukankan      html  css  js  c++  java
  • java连接数据库执行SQL并把查询到的数据保存到磁盘

    import 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("数据收集完成!");
            
        }
    }
  • 相关阅读:
    hdu6148 Valley Numer
    NOI2007 生成树计数
    bzoj3336 Uva10572 Black and White
    hdu1693 eat the trees
    【模板】插头dp
    bzoj4712 洪水
    ZJOI2010 基站选址
    poj2376 Cleaning Shifts
    bzoj4367 [IOI2014]holiday假期
    bzoj4951 [Wf2017]Money for Nothing
  • 原文地址:https://www.cnblogs.com/liujie-/p/14155248.html
Copyright © 2011-2022 走看看