Tuesday, May 27, 2008

How to get Primary Keys with DB2

Commonly when you want to retrieve information of database that you connect, for example primary key, schema name, table name etc. You can use DatabaseMetaData

Code Example:

DatabaseMeataData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getPrimaryKeys(catalog, schema, tablename);

But when your database is DB2. You cann't use DatabaseMetaData (The method can be executed, but it returns an empty ResultSet)

ref :http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.java/rjvjdapi.htm in Table 11

You can use this solution :
This solution select column name of primary key from syscat.keycoluse and syscat.tabconst of DB2.

String SqlStatement = "select colseq, colname from syscat.keycoluse k, syscat.tabconst t where k.constname = t.constname and k.tabname = t.tabname";
conn = Connector.getDBConnection(url, username, password);
pstm = conn.prepareStatement(SqlStatement);
rs = pstm.executeQuery();

ref : http://www-128.ibm.com/developerworks/db2/library/techarticle/dm-0401melnyk/?S_TACT=105AGX11&S_CMP=LP in Table 1

No comments:

Post a Comment