Find the primary key of the data sheet

xiaoxiao2021-03-06  35

Most databases have many primary keys, but the same primary key of the two records is not allowed in a table has the same value. 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 class and java.sql.resultset class can be reflected by calling its GetMetadata method, for example:

// For all classes in java.sql, all types of CONNECTION = ..... DatabaseMetadata dbmeta = connection.getMetadata (); resultset Rset = ..... ResultSetMetadata Rsmeta = RSETMETMETADATA (); java.sql.databaseMetadata class Contains a method of finding a data table primary key. You need to know the name of the table, the Catalog name and the Schema name. If you don't know Catalog and Schema, you can enter "NULL" without using them. For example: // Find a primary key of a table name "comment" // No Catalog or Schema is set to Null ResultSet Pkrset = DBMeta.getPrimaryKeys (NULL, NULL, "Comment"); while (pkrset.next ()) {System.err.Println ("************"); 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, Table "Comment" has a primary key called "comment_id".

Here is the output above the code 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 presence of pk_name is sometimes the name other than the column name. KEY_SEQ represents the order of the primary key. Some databases that use alphabetical sequence save primary keys will return 0 to Key_SEQ.

When creating a generic database app, the primary key for finding a table is basically. JDBC's Metadata class provides the required database reflex mechanism, making the implementation of these applications possible.

(This article is for

One of ZDNET translations, original text has been published

ZDNET website)

转载请注明原文地址:https://www.9cbs.com/read-76698.html

New Post(0)