Most databases have many primary keys, but the same primary key of two records cannot have the same value in a table. You can use Java database connectivity (JDBC) to determine the primary key of a data table.
JDBC has powerful metadata processing capabilities. Java. SQL. Connection and Java. SQL. resultset can be reflected by calling its getmetadata method, for example:
// All classes in Java. SQL
Connection connection = .....
Databasemetadata dbmeta = connection. getmetadata ();
Resultset rset = .....
Resultsetmetadata rsmeta = rset. getmetadata ();
The Java. SQL. databasemetadata class contains a method for finding the primary key of a data table. You need to know the table name, catalog name, and schema name. If you do not know the catalog and schema, you can enter "null" without using them ". For example:
// Search for the primary key of a table named "comment"
// If no catalog or schema exists, it is set to null.
Resultset pkrset = dbmeta. getprimarykeys (null, null, "comment ");
While (Pkrset. Next ()){
System. Err. println ("******* comment ******");
System. Err. println ("table_cat:" + pkrset. GetObject (1 ));
System. Err. println ("table_schem:" + pkrset. GetObject (2 ));
System. Err. println ("table_name:" + pkrset. GetObject (3 ));
System. Err. println ("column_name:" + pkrset. GetObject (4 ));
System. Err. println ("key_seq:" + pkrset. GetObject (5 ));
System. Err. println ("pk_name:" + pkrset. GetObject (6 ));
System. Err. println ("*******************");
}
In this example, the "comment" table has a primary key called "comment_id.
Below are the aboveCodeOutput on MySQL:
* ***** Comment ******
Table_cat:
Table_schem:
Table_name: Comment
Column_name: column_id
Key_seq: 1
Pk_name: column_id
*******************
The reason for the existence of pk_name is that a name other than the column name is sometimes used for a primary key. Key_seq indicates the sequential location of the primary key. Some databases that store primary keys alphabetically return 0 for key_seq.
When creating a common database application, it is very basic to find the primary key of a table. The JDBC metadata class provides the required database reflection mechanism, making the implementation of these applications possible.