1. 程式人生 > >使用JDBC connect獲取數據庫表結構信息

使用JDBC connect獲取數據庫表結構信息

localhost rgs inf cal name tor column info 依賴

1、這是生成代碼的關鍵

引入maven依賴

   <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>

2、編寫JAVA類

package com.yyj.mybties.jdbc;


import java.sql.Connection;
import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * 獲取數據庫中表的結構 */ public class JDBCdemo { public static void main(String[] args) { String driver = "com.mysql.jdbc.Driver"; String URL
= "jdbc:mysql://localhost:3306/mybase"; Connection con = null; List<String> tableNames = new ArrayList(); try { con= DriverManager.getConnection(URL,"root",""); getTableInfo(con,"users"); } catch(Exception e) { System.out.println("Connect fail:" + e.getMessage()); } }
private static void getTableInfo(Connection con,String tableName) throws SQLException { DatabaseMetaData metaData = con.getMetaData(); ResultSet colRet = metaData.getColumns(null, "%", tableName, "%"); String columnName; String columnType; 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); } System.out.println("\n"); } }

執行結果

技術分享圖片

使用JDBC connect獲取數據庫表結構信息