JDBC Gets the table structure, primary key

Source: Internet
Author: User
Tags mysql code one table

JDBC Gets the table structure, primary keyTags: jdbctablenullschema database mysql2012-02-16 22:13 11889 People read comments (0) favorite reports Classification:Java (+)

Suppose there's a con.
DatabaseMetaData Dbmd = Con.getmetadata ();
rs = Dbmd.getcolumns (Con.getcatalog (), schema, tableName, NULL);
Rs.getstring (data_type) Java.sql.Types SQL type
The size of the rs.getstring (column_size) column. For char or date types, the size of the column is the maximum number of characters, and for numeric and decimal types, the column size is precision.
Rs.getstring (decimal_digits) Number of digits in the fractional part

JDBC uses metadata to get information about the specific table. You can query which tables are in the database, what fields are in the table, the properties of the fields, and so on. In metadata, this information is stored in the resultset and returned to the user through a series of getxxx functions. About metadata There are also many online, here I just from the perspective of my own learning to record the simple use of JDBC and get data table related information methods.
First of all, Http://hometown.aol.com/kgb1001001/Articles/JDBCMetadata/JDBC_Metadata.htm here's a name called "Understanding JDBC." MetaData "The article, explained well.

Here is the code for getting the table information under my JDBC. I am using MySQL 5.0 as the test platform.

1. JDBC Connection MySQL code is very standard, very simple.
Class.forName ("Com.mysql.jdbc.Driver"). newinstance ();
Connection conn = DriverManager
. getconnection ("jdbc:mysql://localhost/test?user=root&password=123456");

2. Here is the information for getting the table.
M_dbmetadata = M_connection.getmetadata ();
ResultSet Tableret = M_dbmetadata.gettables (null, "%", m_tablename,new string[]{"TABLE"});
Where "%" means the meaning of *, that is, any meaning. Where M_tablename is the name of the data table to get, if you want to get all the names of the table, you can use "%" as a parameter.

3. Extract the name of the table.
while (Tableret.next) System.out.println (tableret.getstring ("table_name"));

by GetString ("table_name"), you can get the name of the table.
As can be seen from here, JDBC is returning all of its results, in a table-like memory structure, in front of the Gettables interface, where the field of table_name is the name of each table.

4. Extracting the names and types of fields within a table
String ColumnName;
String ColumnType;
ResultSet Colret = M_dbmetadata.getcolumns (null, "%", m_tablename, "%");
while (Colret.next ()) {
ColumnName = colret.getstring ("column_name");
ColumnType = colret.getstring ("type_name");
int datasize = Colret.getint ("Column_size");
int digits = Colret.getint ("Decimal_digits");
int nullable = Colret.getint ("nullable");
System.out.println (columnname+ "" +columntype+ "" +datasize+ "" +digits+ "" +
Nullable);
}

JDBC inside the GetColumns interface, implementation of the field query. As with Gettables, "%" denotes all arbitrary (fields), and M_tablename is the name of the data table.

GetColumns's return also puts all the fields into a similar in-memory table, and column_name is the name of the field, Type_name is the data type, such as "int", "int unsigned" and so on, Column_size returns an integer, Is the length of the field, such as the field of the defined int (8), the return is 8, the last nullable, the return 1 means that it can be null, and 0 means not NULL.
-------------------
Most databases have many primary keys, but the same primary key for two records is not allowed in one table with the same value. You can use Java Database Connectivity (JDBC) to determine the primary key of a data table.
JDBC has powerful meta-data processing capabilities. The Java.sql.Connection class and the Java.sql.ResultSet class can be reflected by calling their GetMetaData method, for example:
For all the 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 name of the table, the catalog name, and the schema name. If you do not know the catalog and schema, you can enter "null" without using them. For example:
Find the primary key for a table named "Comment"
No catalog or schema, all 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 table "Comment" has a primary key called "comment_id".
Here is the output of the above 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 that names other than column names are sometimes used for a primary key. The key_seq represents the sequential position of the primary key. Some databases that use alphabetical order to save primary keys return 0 for Key_seq.
When creating a common database application, it is essential to find the primary key for a table. The metadata class of JDBC provides the required database reflection mechanism, making it possible for these applications to be implemented.
(This article is one of the series of articles for ZDNet translation, the original text has been published on the ZDNet website)

JDBC Gets the table structure, primary key

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.