Atitit 获取数据库表主键功能的实现 数据库模块 艾提拉attilax总结
package com.attilax.sql;
import java.sql.Connection;
import com.attilax.util.MybatisUtil;
public class DbMetaServiceTest {
public static void main(String[] args) {
Connection conn= newMybatisUtil().get_conn();
System.out.println(new DbMetaService().getPrimaryKey (conn,"","vaj1"));
}
public String getPrimaryKey(Connection conn, String dbName, String tablename) {
Map m = Maps.newLinkedHashMap();
m.put("db", dbName);
m.put("$table", tablename);
List<Map> li = getPrimaryKeys(conn,dbName,tablename);
String COLUMN_NAME = (String) li.get(0).get("COLUMN_NAME");
if(COLUMN_NAME==null)
COLUMN_NAME = (String) li.get(0).get("column_name"); //pgsql
return COLUMN_NAME;
//return (String) li.get(0).get("COLUMN_NAME");
}
private List<Map> getPrimaryKeys(Connection conn, String dbName, String tablename) {
// TODO Auto-generated method stub
return getPrimaryKeys__all(conn,tablename);
}
}
public List getPrimaryKeys__all(Connection conn,Object tab) {
// DBX dbx = IocX4casher.getBean(DBX.class);
java.sql.DatabaseMetaData dbmd = null;
try {
dbmd = conn.getMetaData();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
// databaseMetaData.getColumns(localCatalog, localSchema,
// localTableName, null);
//String catalog = (String) req.get("db");
ResultSet rs = null;
try {
// = getTableName(req);
// rs = dbmd.getPrimaryKeys(null, "%", tab.toString()); mysql
//rs = dbmd.getPrimaryKeys("%", "%", tab.toString()); //pgsqql
rs = dbmd.getPrimaryKeys("*", "public", tab.toString()); //pgsqql pgsql should add schmael
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
List li = null;
try {
li = new DBX().convertList(rs);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
throw new RuntimeException(e1);
}
return li;
}