jdbc连接获取表名称

1,Class.forName可以替换为mysql之类其他的数据库驱动

public Connection connect(String url,String username,String pw, int dbType) throws SQLException {
        Connection con = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return DriverManager.getConnection(url,username,pw);
    }

2,getTables()第一个参数是数据库名称,如果是oracle为null,目前只测试了oracle和mysql,mysql传数据库名称,oracle传null

public List<Map<String,Object>> getTableNameList(Connection conn,String username, String databaseName, int databaseType) throws SQLException {
        DatabaseMetaData dbmd = conn.getMetaData();
        if (Constant.DATABASE_TYPE_MYSQL != databaseType){
            databaseName = null;
        }
        ResultSet rs = dbmd.getTables(databaseName, username.toUpperCase(), "%", new String[] { "TABLE" });
        List<Map<String,Object>> tableNameList = new ArrayList<Map<String,Object>>();
        while (rs.next()) {
        Map<String, Object> map = new HashMap<String, Object>(); 
        map.put("TABLE_NAME", rs.getString("TABLE_NAME"));
        tableNameList.add(map);
        }
        return tableNameList;
    }

 3,调用

Connection con = null;
        List<Map<String,Object>> tableNameList = null;
        try {
            con = connect(url,username,pw,databaseType);
            tableNameList = getTableNameList(con,username, databaseName, databaseType);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                e.printStackTrace();
                }
            }
        }

 

Connection con = null;
List<Map<String,Object>> tableNameList = null;
try {
con = connect(url,username,pw,databaseType);
tableNameList = getTableNameList(con,username, databaseName, databaseType);
posted @ 2018-11-09 11:23  無玑小姐  阅读(1596)  评论(0编辑  收藏  举报