jdbc連接獲取表名稱
阿新 • • 發佈:2018-11-09
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, intdatabaseType) 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);