java获取Oracle所有库名, 库里所有表名, 表里所有字段名

package com.sb.test;

import org.junit.Before;
import org.junit.Test;

import java.sql.*;

public class OracleTest {


    //jdbc:oracle:thin:@localhost:1521:zhyl
    private String url="jdbc:oracle:thin:@数据库IP:1521:数据库实例名字";
    //服务器地址:,端口号:1521,数据库实例名字:zhyl。

    private String username="用户名";

    private String password="密码";

    private Connection conn=null;
    private static Statement stmt = null;

    @Before
    public void init(){
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn= DriverManager.getConnection(url,username,password);
            stmt = conn.createStatement();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 查询获取所有数据库名
     */
    @Test
    public void findAllDatabases(){
        try {
            ResultSet resultSet = stmt.executeQuery("select * from v$tablespace");
            while(resultSet.next()){//如果对象中有数据,就会循环打印出来
                System.out.println(resultSet.getString("name"));
            }
            resultSet.close();
            stmt.close();
            resultSet.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 查询获取数据库所有表名
     */
    @Test
    public void findAllTables(){
        try {
            ResultSet resultSet = stmt.executeQuery("select TABLE_NAME from all_tables WHERE owner='数据库名字'");
            while(resultSet.next()){//如果对象中有数据,就会循环打印出来
                System.out.println(resultSet.getString("TABLE_NAME"));
            }
            resultSet.close();
            stmt.close();
            resultSet.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询获取数据库表的所有字段
     */
    @Test
    public void findAllColumns(){

        try {
            ResultSet resultSet = stmt.executeQuery("select t.column_name from user_col_comments t where t.table_name = '表名'");
            while(resultSet.next()){//如果对象中有数据,就会循环打印出来
                System.out.println(resultSet.getString("column_name"));
            }
			resultSet.close();
            stmt.close();
            resultSet.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java)