程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> Oracle數據庫 >> Oracle教程 >> JAVA查詢Oracle數據庫導出成txt文本

JAVA查詢Oracle數據庫導出成txt文本

編輯:Oracle教程

JAVA查詢Oracle數據庫導出成txt文本


import java.io.FileOutputStream;
import java.io.PrintStream;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class sqltotxt {
	public static void main(String[] args) throws Exception {
        Connection conn = null;
        String sql;
        String url="jdbc:oracle:thin:@xx.xx.xx.xx:1521:ORAC";
        /*指定數據的用戶名和密碼*/  
        String username="XXX";  
        String password="XXX";
 
        try {
 
            Class.forName("oracle.jdbc.driver.OracleDriver");
      
            conn = DriverManager.getConnection(url,username,password);
      
            Statement stmt = conn.createStatement();
            sql = "select * from Table_name";
            ResultSet rs = stmt.executeQuery(sql);// executeUpdate語句會返回一個受影響的行數,如果返回-1就沒有成功
            
            FileOutputStream fos = new FileOutputStream("E:\\ok.txt",true);
            //fos.write(rs.getInt(1));
            PrintStream p = new PrintStream(fos);
            while (rs.next()) {
                System.out.println(rs.getInt(1) +","+rs.getInt(2) +"," +rs.getInt(3) +","+rs.getString(4) + "," + rs.getString(5));// 入如果返回的是int類型可以用getInt()
            
                String sb = rs.getInt(1) +","+rs.getInt(2) +"," +rs.getInt(3) +","+rs.getString(4) + "," + rs.getString(5);
                //FileOutputStream fos = new FileOutputStream("E:\\ok.txt",true);
                //fos.write(rs.getInt(1));
                //PrintStream p = new PrintStream(fos);
                p.println(sb);
            }
         
            p.close();
            fos.flush();
            
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            conn.close();
        }
 
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved