Java 通過JDBC查詢數據庫表結構(字段名稱,類型,長度等)

我們如何知道,我們訪問的數據庫的表,有哪些字段,字段的類型是什麼,長度限制是什麼?

在實際工作中,我就遇到過,要做動態sql,比如insert,如果是數字就不要加引號,如果是字符就要加引號,還比如做基於數據庫表的代碼生成器等。我們都可能需要查表的表結構。

下面我就介紹一種通過JAVA最原始的JDBC查表結構的方法。

Java 通過JDBC查詢數據庫表結構(字段名稱,類型,長度等)

在JDBC中,PreparedStatement.executeQuery().getMetaData();後,我們可以通過ResultSetMetaData對象查詢返回結果集的源數據信息,也就是表結構信息。

示例代碼如下:

 

 

[java] view plaincopy
  1. package astar.sutil.db;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSetMetaData;  
  7. import java.sql.SQLException;  
  8. import java.util.ArrayList;  
  9. import java.util.List;  
  10.   
  11. /**   
  12. * @author 魯炬 
  13. * 
  14. */  
  15. public class DbMetaDataUtilTest {  
  16.   
  17.   public static void main(String[] args) throws SQLException, ClassNotFoundException {  
  18.     String user = "user";  
  19.     String password = "pwd";  
  20.     String jdbcDriver = "com.ibm.db2.jcc.DB2Driver";  
  21.     String jdbcUrl = "jdbc:db2://localhost:50000/DBNAME";  
  22.     Connection conn = null;  
  23.     Class.forName(jdbcDriver);  
  24.     conn = DriverManager.getConnection(jdbcUrl, user, password);  
  25.   
  26.     PreparedStatement pst = null;  
  27.     try {  
  28.       pst = conn.prepareStatement("select * from t_table where 1=2");  
  29.       ResultSetMetaData rsd = pst.executeQuery().getMetaData();  
  30.       for(int i = 0; i < rsd.getColumnCount(); i++) {  
  31.         System.out.print("java類型:"+rsd.getColumnClassName(i + 1));  
  32.         System.out.print("  數據庫類型:"+rsd.getColumnTypeName(i + 1));  
  33.         System.out.print("  字段名稱:"+rsd.getColumnName(i + 1));  
  34.         System.out.print("  字段長度:"+rsd.getColumnDisplaySize(i + 1));  
  35.         System.out.println();  
  36.       }  
  37.     } catch(SQLException e) {  
  38.       throw new RuntimeException(e);  
  39.     } finally {  
  40.       try {  
  41.         pst.close();  
  42.         pst = null;  
  43.       } catch(SQLException e) {  
  44.         throw new RuntimeException(e);  
  45.       }  
  46.     }  
  47.   
  48.   }  
  49.   
  50. }  


 


以上代碼運行打印如下:

 

[plain] view plaincopy
  1. java類型:java.lang.String  數據庫類型:VARCHAR  字段名稱:CORP_CODE  字段名稱:20  
  2. java類型:java.lang.String  數據庫類型:VARCHAR  字段名稱:CORP_NAME  字段名稱:100  
  3. java類型:java.lang.String  數據庫類型:VARCHAR  字段名稱:SIMPLY_NAME  字段名稱:50  
  4. java類型:java.lang.String  數據庫類型:CHAR  字段名稱:CORP_LEVEL  字段名稱:1  
  5. java類型:java.lang.String  數據庫類型:VARCHAR  字段名稱:SUP_CORP_CODE  字段名稱:20  
  6. java類型:java.lang.String  數據庫類型:VARCHAR  字段名稱:PROVINCE  字段名稱:8  
  7. java類型:java.lang.String  數據庫類型:VARCHAR  字段名稱:STAT_CODE  字段名稱:8  
  8. java類型:java.lang.String  數據庫類型:CHAR  字段名稱:CORP_KIND  字段名稱:4  
  9. java類型:java.lang.String  數據庫類型:CHAR  字段名稱:IS_LEAF  字段名稱:1  
  10. java類型:java.lang.String  數據庫類型:CHAR  字段名稱:IS_USE  字段名稱:1  
  11. java類型:java.lang.String  數據庫類型:CHAR  字段名稱:IS_UPDATE  字段名稱:1  
  12. java類型:java.lang.Integer  數據庫類型:SMALLINT  字段名稱:ORDER_CODE  字段名稱:6  
  13. java類型:java.lang.String  數據庫類型:VARCHAR  字段名稱:MAP_REGIE_CODE  字段名稱:20  
  14. java類型:java.lang.String  數據庫類型:CHAR  字段名稱:IS_SUPER  字段名稱:1  
  15. java類型:java.lang.Integer  數據庫類型:SMALLINT  字段名稱:DISPLAY_ID  字段名稱:6  
  16. java類型:java.lang.String  數據庫類型:CHAR  字段名稱:IS_GIS  字段名稱:1  


 

更多詳細的屬性輸出可以讀一下ResultSetMetaData對象的源碼。

 

[java] view plaincopy
  1. /* 
  2.  * @(#)ResultSetMetaData.java   1.33 05/12/01 
  3.  * 
  4.  * Copyright 2006 Sun Microsystems, Inc. All rights reserved. 
  5.  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 
  6.  */  
  7.   
  8. package java.sql;  
  9.   
  10. /** 
  11.  * An object that can be used to get information about the types  
  12.  * and properties of the columns in a <code>ResultSet</code> object. 
  13.  * The following code fragment creates the <code>ResultSet</code> object rs, 
  14.  * creates the <code>ResultSetMetaData</code> object rsmd, and uses rsmd 
  15.  * to find out how many columns rs has and whether the first column in rs 
  16.  * can be used in a <code>WHERE</code> clause. 
  17.  * <PRE> 
  18.  * 
  19.  *     ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2"); 
  20.  *     ResultSetMetaData rsmd = rs.getMetaData(); 
  21.  *     int numberOfColumns = rsmd.getColumnCount(); 
  22.  *     boolean b = rsmd.isSearchable(1); 
  23.  * 
  24.  * </PRE> 
  25.  */  
  26.   
  27. public interface ResultSetMetaData extends Wrapper {  
  28.   
  29.     /** 
  30.      * Returns the number of columns in this <code>ResultSet</code> object. 
  31.      * 
  32.      * @return the number of columns 
  33.      * @exception SQLException if a database access error occurs 
  34.      */  
  35.     int getColumnCount() throws SQLException;  
  36.   
  37.     /** 
  38.      * Indicates whether the designated column is automatically numbered. 
  39.      * 
  40.      * @param column the first column is 1, the second is 2, ... 
  41.      * @return <code>true</code> if so; <code>false</code> otherwise 
  42.      * @exception SQLException if a database access error occurs 
  43.      */  
  44.     boolean isAutoIncrement(int column) throws SQLException;  
  45.   
  46.     /** 
  47.      * Indicates whether a column's case matters. 
  48.      * 
  49.      * @param column the first column is 1, the second is 2, ... 
  50.      * @return <code>true</code> if so; <code>false</code> otherwise 
  51.      * @exception SQLException if a database access error occurs 
  52.      */  
  53.     boolean isCaseSensitive(int column) throws SQLException;      
  54.   
  55.     /** 
  56.      * Indicates whether the designated column can be used in a where clause. 
  57.      * 
  58.      * @param column the first column is 1, the second is 2, ... 
  59.      * @return <code>true</code> if so; <code>false</code> otherwise 
  60.      * @exception SQLException if a database access error occurs 
  61.      */  
  62.     boolean isSearchable(int column) throws SQLException;  
  63.   
  64.     /** 
  65.      * Indicates whether the designated column is a cash value. 
  66.      * 
  67.      * @param column the first column is 1, the second is 2, ... 
  68.      * @return <code>true</code> if so; <code>false</code> otherwise 
  69.      * @exception SQLException if a database access error occurs 
  70.      */  
  71.     boolean isCurrency(int column) throws SQLException;  
  72.   
  73.     /** 
  74.      * Indicates the nullability of values in the designated column.         
  75.      * 
  76.      * @param column the first column is 1, the second is 2, ... 
  77.      * @return the nullability status of the given column; one of <code>columnNoNulls</code>, 
  78.      *          <code>columnNullable</code> or <code>columnNullableUnknown</code> 
  79.      * @exception SQLException if a database access error occurs 
  80.      */  
  81.     int isNullable(int column) throws SQLException;  
  82.   
  83.     /** 
  84.      * The constant indicating that a 
  85.      * column does not allow <code>NULL</code> values. 
  86.      */  
  87.     int columnNoNulls = 0;  
  88.   
  89.     /** 
  90.      * The constant indicating that a 
  91.      * column allows <code>NULL</code> values. 
  92.      */  
  93.     int columnNullable = 1;  
  94.   
  95.     /** 
  96.      * The constant indicating that the 
  97.      * nullability of a column's values is unknown. 
  98.      */  
  99.     int columnNullableUnknown = 2;  
  100.   
  101.     /** 
  102.      * Indicates whether values in the designated column are signed numbers. 
  103.      * 
  104.      * @param column the first column is 1, the second is 2, ... 
  105.      * @return <code>true</code> if so; <code>false</code> otherwise 
  106.      * @exception SQLException if a database access error occurs 
  107.      */  
  108.     boolean isSigned(int column) throws SQLException;  
  109.   
  110.     /** 
  111.      * Indicates the designated column's normal maximum width in characters. 
  112.      * 
  113.      * @param column the first column is 1, the second is 2, ... 
  114.      * @return the normal maximum number of characters allowed as the width 
  115.      *          of the designated column 
  116.      * @exception SQLException if a database access error occurs 
  117.      */  
  118.     int getColumnDisplaySize(int column) throws SQLException;  
  119.   
  120.     /** 
  121.      * Gets the designated column's suggested title for use in printouts and 
  122.      * displays. The suggested title is usually specified by the SQL <code>AS</code>  
  123.      * clause.  If a SQL <code>AS</code> is not specified, the value returned from  
  124.      * <code>getColumnLabel</code> will be the same as the value returned by the  
  125.      * <code>getColumnName</code> method. 
  126.      * 
  127.      * @param column the first column is 1, the second is 2, ... 
  128.      * @return the suggested column title 
  129.      * @exception SQLException if a database access error occurs 
  130.      */  
  131.     String getColumnLabel(int column) throws SQLException;    
  132.   
  133.     /** 
  134.      * Get the designated column's name. 
  135.      * 
  136.      * @param column the first column is 1, the second is 2, ... 
  137.      * @return column name 
  138.      * @exception SQLException if a database access error occurs 
  139.      */  
  140.     String getColumnName(int column) throws SQLException;  
  141.   
  142.     /** 
  143.      * Get the designated column's table's schema. 
  144.      * 
  145.      * @param column the first column is 1, the second is 2, ... 
  146.      * @return schema name or "" if not applicable 
  147.      * @exception SQLException if a database access error occurs 
  148.      */  
  149.     String getSchemaName(int column) throws SQLException;  
  150.   
  151.     /** 
  152.      * Get the designated column's specified column size.  
  153.      * For numeric data, this is the maximum precision.  For character data, this is the length in characters.  
  154.      * For datetime datatypes, this is the length in characters of the String representation (assuming the  
  155.      * maximum allowed precision of the fractional seconds component). For binary data, this is the length in bytes.  For the ROWID datatype,  
  156.      * this is the length in bytes. 0 is returned for data types where the 
  157.      * column size is not applicable. 
  158.      * 
  159.      * @param column the first column is 1, the second is 2, ... 
  160.      * @return precision 
  161.      * @exception SQLException if a database access error occurs 
  162.      */  
  163.     int getPrecision(int column) throws SQLException;  
  164.   
  165.     /** 
  166.      * Gets the designated column's number of digits to right of the decimal point. 
  167.      * 0 is returned for data types where the scale is not applicable. 
  168.      * 
  169.      * @param column the first column is 1, the second is 2, ... 
  170.      * @return scale 
  171.      * @exception SQLException if a database access error occurs 
  172.      */  
  173.     int getScale(int column) throws SQLException;     
  174.   
  175.     /** 
  176.      * Gets the designated column's table name.  
  177.      * 
  178.      * @param column the first column is 1, the second is 2, ... 
  179.      * @return table name or "" if not applicable 
  180.      * @exception SQLException if a database access error occurs 
  181.      */  
  182.     String getTableName(int column) throws SQLException;  
  183.   
  184.     /** 
  185.      * Gets the designated column's table's catalog name. 
  186.      * 
  187.      * @param column the first column is 1, the second is 2, ... 
  188.      * @return the name of the catalog for the table in which the given column 
  189.      *          appears or "" if not applicable 
  190.      * @exception SQLException if a database access error occurs 
  191.      */  
  192.     String getCatalogName(int column) throws SQLException;  
  193.   
  194.     /** 
  195.      * Retrieves the designated column's SQL type. 
  196.      * 
  197.      * @param column the first column is 1, the second is 2, ... 
  198.      * @return SQL type from java.sql.Types 
  199.      * @exception SQLException if a database access error occurs 
  200.      * @see Types 
  201.      */  
  202.     int getColumnType(int column) throws SQLException;  
  203.   
  204.     /** 
  205.      * Retrieves the designated column's database-specific type name. 
  206.      * 
  207.      * @param column the first column is 1, the second is 2, ... 
  208.      * @return type name used by the database. If the column type is 
  209.      * a user-defined type, then a fully-qualified type name is returned. 
  210.      * @exception SQLException if a database access error occurs 
  211.      */  
  212.     String getColumnTypeName(int column) throws SQLException;  
  213.   
  214.     /** 
  215.      * Indicates whether the designated column is definitely not writable. 
  216.      * 
  217.      * @param column the first column is 1, the second is 2, ... 
  218.      * @return <code>true</code> if so; <code>false</code> otherwise 
  219.      * @exception SQLException if a database access error occurs 
  220.      */  
  221.     boolean isReadOnly(int column) throws SQLException;  
  222.   
  223.     /** 
  224.      * Indicates whether it is possible for a write on the designated column to succeed. 
  225.      * 
  226.      * @param column the first column is 1, the second is 2, ... 
  227.      * @return <code>true</code> if so; <code>false</code> otherwise 
  228.      * @exception SQLException if a database access error occurs 
  229.      */  
  230.     boolean isWritable(int column) throws SQLException;  
  231.   
  232.     /** 
  233.      * Indicates whether a write on the designated column will definitely succeed.   
  234.      * 
  235.      * @param column the first column is 1, the second is 2, ... 
  236.      * @return <code>true</code> if so; <code>false</code> otherwise 
  237.      * @exception SQLException if a database access error occurs 
  238.      */  
  239.     boolean isDefinitelyWritable(int column) throws SQLException;  
  240.   
  241.     //--------------------------JDBC 2.0-----------------------------------  
  242.   
  243.     /** 
  244.      * <p>Returns the fully-qualified name of the Java class whose instances  
  245.      * are manufactured if the method <code>ResultSet.getObject</code> 
  246.      * is called to retrieve a value  
  247.      * from the column.  <code>ResultSet.getObject</code> may return a subclass of the 
  248.      * class returned by this method. 
  249.      * 
  250.      * @param column the first column is 1, the second is 2, ... 
  251.      * @return the fully-qualified name of the class in the Java programming 
  252.      *         language that would be used by the method  
  253.      * <code>ResultSet.getObject</code> to retrieve the value in the specified 
  254.      * column. This is the class name used for custom mapping. 
  255.      * @exception SQLException if a database access error occurs 
  256.      * @since 1.2 
  257.      */  
  258.     String getColumnClassName(int column) throws SQLException;  
  259. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章