最近做自动化增删改查,获取表中的主键字段名非常有用
仅支持mysql
package com.litong.jfinal.service; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.jfinal.plugin.activerecord.Config; import com.jfinal.plugin.activerecord.DbKit; /** * @author bill robot * @date 2020年8月27日_下午2:55:52 * @version 1.0 * @desc */ public class DbService { public String[] gerPrimaryKey(String tableName) { Config config = DbKit.getConfig(); Connection conn = null; try { conn = config.getConnection(); } catch (SQLException e1) { e1.printStackTrace(); } String sql = "SHOW CREATE TABLE " + tableName; ResultSet rs = null; try { PreparedStatement pre = conn.prepareStatement(sql); rs = pre.executeQuery(); if (rs.next()) { return getPrimaryKeyFromResultSet(rs); } } catch (Exception e) { e.printStackTrace(); } return null; } private String[] getPrimaryKeyFromResultSet(ResultSet rs) throws SQLException { // 1.获取建表语句 String string = rs.getString(2); // 正则匹配数据 Pattern pattern = Pattern.compile("PRIMARY KEY \\(\\`(.*)\\`\\)"); Matcher matcher = pattern.matcher(string); matcher.find(); String data = matcher.group(); // -->PRIMARY KEY (`id`) // 过滤对于字符 data = data.replaceAll("\\`|PRIMARY KEY \\(|\\)", ""); // 拆分字符 String[] stringArr = data.split(",");// -->["id"] return stringArr; } }
如果数据库只有1个主键,字段名是id,返回的是 ["id"]