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();
}
}
}