1. 程式人生 > 其它 >JDBC連線MySQL資料庫,讀取表結構資訊

JDBC連線MySQL資料庫,讀取表結構資訊

JDBC連線資料庫示例:

package com.sjx.test;

import java.sql.*;

public class DemoDB {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql:///test?serverTimezone=UTC";
        Connection conn = DriverManager.getConnection(url, "root", "root");
        //有預處理sql語句的功能
        String sql = "select * from person where pid=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1,1);
        ResultSet resultSet = ps.executeQuery();

        while (resultSet.next()){
            String name = resultSet.getString("name");
            System.out.println(name);
        }
    }
}

JDBC獲取表結構示例:

@Test
public void test() throws Exception {
    Connection conn = JdbcUtils.getConnection();
    DatabaseMetaData metaData = conn.getMetaData();
    System.out.println(conn.getCatalog());
    //資料庫型別 MYSQL ORACLE
    System.out.println(metaData.getDatabaseProductName());
    //資料庫版本號 8.0.15
    System.out.println(metaData.getDatabaseProductVersion());
    //資料庫大版本 8
    System.out.println(metaData.getDatabaseMajorVersion());
    //jdbc連線的url
    System.out.println(metaData.getURL());
    String[] types = {"TABLE"};
    //獲取所有表
    ResultSet rs = metaData.getTables(conn.getCatalog(), null, null, null);
    while (rs.next()) {
        String tableName = rs.getString("TABLE_NAME"); //表名
        String tableType = rs.getString("TABLE_TYPE"); //表型別
        String remarks = rs.getString("REMARKS"); //表備註
        System.out.println("表名:" + tableName + "   表型別: " + tableType + "   表註釋:" + remarks);
    }
}

輸出結果:

test
MySQL
5.5.40
5
jdbc:mysql:///test?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
表名:person 表型別: TABLE 表註釋:
表名:test 表型別: TABLE 表註釋:

1+1>2