java 导出 Oracle

import java.io.FileWriter;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Main {

	private static final String TYPE_MARK = "-1";
	
	private static String SQL = 
		"SELECT DBMS_METADATA.GET_DDL(U.OBJECT_TYPE, U.object_name), U.OBJECT_TYPE " +
		"FROM USER_OBJECTS U " +
		"where U.OBJECT_TYPE = 'TABLE' " +
		"or U.OBJECT_TYPE = 'VIEW' " +
		"or U.OBJECT_TYPE = 'INDEX' " +
		"or U.OBJECT_TYPE = 'PROCEDURE' " +
		"or U.OBJECT_TYPE = 'SEQUENCE' " +
		"or U.OBJECT_TYPE = 'TRIGGER' " +
		"order by U.OBJECT_TYPE desc";
	
	private static String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
	private static String USERNAME = "scott";
	private static String PASSWORD = "tiger";
	private static String OUTFILE = "tables.sql";
	
	public static void main(String[] args) throws Exception {
		FileWriter fw = new FileWriter(OUTFILE);
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		Statement statement = con.createStatement();
		ResultSet rs = statement.executeQuery(SQL);
		Clob ddl;
		String type = TYPE_MARK;
		int count = 0;
		List<String> list = new ArrayList<String>();
		while(rs.next()) {
			ddl = rs.getClob(1);
			fw.write(ddl.getSubString(1L, (int)ddl.length()));
			if(!rs.getString(2).equals(type)) {
				if(!type.equals(TYPE_MARK)) {
					list.add(type + "," + count);
					type = rs.getString(2);
					count = 1;
				} else {
					type = rs.getString(2);
					count ++;
				}
			} else
				count ++;
		}
		list.add(type + "," + count);
		fw.flush();
		fw.close();
		rs.close();
		statement.close();
		con.close();
		for(String type1 : list)
			System.out.print(type1.split(",")[0] + ":" + type1.split(",")[1] + ";");
		System.out.println();
	}

}

你可能感兴趣的:(oracle)