核心语句: ResultSet rs=conn.getMetaData().getPrimaryKeys(null, null, this.table); String pkStr = rs.getString("COLUMN_NAME");
【功用】
在Java程序中,以JDBC的方式获取表的主键
【代码】
主键寻找器代码,核心语句为下面标红的粗体字:
package com.hy.lab.primarykey;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class PrimaryKeyFinder {
private Connection conn;
private String table;
public PrimaryKeyFinder(Connection conn,String table){
this.conn=conn;
this.table=table;
}
public void printPrimaryKeys(){
try(ResultSet rs=this.conn.getMetaData().getPrimaryKeys(null, null, this.table)){
if (null == rs) {
System.out.println(String.format("表%s没有主键",this.table));
return;
}
List<String> pks=new ArrayList<String>();
while (rs.next()) {
String pkStr = rs.getString("COLUMN_NAME");
pks.add(pkStr);
}
String result=String.format("表%s有%d个主键:%s",this.table,pks.size(),String.join(",",pks));
System.out.println(result);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
try(Connection conn=DbUtil.getConn()){
PrimaryKeyFinder finder=new PrimaryKeyFinder(conn,"emp625_3key".toUpperCase());
finder.printPrimaryKeys();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
DBUtil工具类代码:
package com.hy.lab.primarykey;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbUtil {
//-- 以下为连接Oracle数据库的四大参数
private static final String DRIVER = "oracle.jdbc.OracleDriver";
private static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521/orcl";
private static final String USER = "luna";
private static final String PSWD = "1234";
public static Connection getConn() throws Exception{
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(URL, USER, PSWD);
return conn;
}
}
【运行情况】
表EMP625_1KEY有1个主键:ID
表EMP625_NOKEY有0个主键:
表EMP625_3KEY有3个主键:F1,F2,ID
【供测试用的建表语句】
create table emp625_1key(
id number(10),
f1 nvarchar2(10),
primary key(id)
);
create table emp625_3key(
id number(10),
f1 nvarchar2(10),
f2 nvarchar2(10),
f3 nvarchar2(10),
f4 nvarchar2(10),
f5 nvarchar2(10),
f6 nvarchar2(10),
f7 nvarchar2(10),
f8 nvarchar2(10),
f9 nvarchar2(10),
primary key(id,f1,f2)
);
create table emp625_nokey(
id number(10),
f1 nvarchar2(10),
f2 nvarchar2(10),
f3 nvarchar2(10)
);
【参考资料】
https://www.it610.com/article/1292739578821681152.htm
END