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 表注释:

posted @ 2021-10-29 13:58  novae  阅读(616)  评论(0编辑  收藏  举报