【Java】jdbc获取主键的字段名
/** * 获取主键的字段名 * @param tableName 表名 * @return 表的主键字段名 */ public String getPK(String tableName) { String PKName = null; try { DatabaseMetaData dmd = conn.getMetaData(); ResultSet rs = dmd.getPrimaryKeys(null, "%", tableName); rs.next(); PKName = rs.getString("column_name"); rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } // //方法二 // String sql = String.format("show index from %s", tableName); // try { // PreparedStatement ps = conn.prepareStatement(sql); // ResultSet rs = ps.executeQuery(); // rs.next(); // PKName = rs.getString("column_name"); // rs.close(); // ps.close(); // } catch (SQLException throwables) { // throwables.printStackTrace(); // } return PKName; }