spring jdbcTemplate中獲取jdbc Connection並執行操作
阿新 • • 發佈:2018-12-09
實際應用例子在專案中需要獲取資料庫中元資料相關資訊,比如表名,欄位名,長度等jdbcTemplate 可以通過SqlRowSetMetaData 可以獲取到部分元資料,但是不能獲取備註資訊(comment中的內容)
已經有jdbcTemplate物件,只需要通過jdbcTemplate獲取jdbc Connection即可獲取全部資訊
程式碼示例如下:
List<Dtfd> dtfds = new ArrayList<Dtfd>(); dwJdbcTemplate.execute(new ConnectionCallback<List<Dtfd>>() { @Override public List<Dtfd> doInConnection(Connection con) throws SQLException, DataAccessException { DatabaseMetaData dbmd = con.getMetaData(); // 表名列表 String[] types = { "TABLE" }; ResultSet tableRS = dbmd.getTables(null, null, dtco, types); tableRS.last(); int cnt = tableRS.getRow(); tableRS.beforeFirst(); if (1 != cnt) { return null; } while (tableRS.next()) { String tablename = tableRS.getString("TABLE_NAME"); ResultSet resultSet = dbmd.getColumns(null, null, tablename, null); while (resultSet.next()) { String name = resultSet.getString("COLUMN_NAME"); String type = resultSet.getString("TYPE_NAME"); String colRemarks = resultSet.getString("REMARKS"); int size = resultSet.getInt("COLUMN_SIZE"); Dtfd dtfd = new Dtfd(); dtfd.setDtco(dtco); dtfd.setColu(name); dtfd.setClna(colRemarks); dtfd.setDttp(type); dtfd.setDtle(size); dtfds.add(dtfd); } } return null; } }); return dtfds;