解决问题:JDBC判断指定数据库是否存在某张表

探讨了SpringBoot2.1.x集成Elastic-Job在MySQL环境下,因其他数据库存在同名表导致无法自动创建JOB_EXECUTION_LOG等表的问题。通过分析发现,问题源于连接URL未设置nullCatalogMeansCurrent=true参数,导致JDBC跨库查询。解决方案是在URL中加入此参数,确保仅在目标数据库内查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 驱动: com.mysql.cj.jdbc.Driver

 正确查询方法:

public class JdbcConnection {
    public static Connection getConn() {
        String driver = "com.mysql.cj.jdbc.Driver";
        // 1.url
        String url = "jdbc:mysql://localhost:3306/ump?useSSL=false&nullCatalogMeansCurrent=true";
        String username = "root";
        String password = "123456";
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void main(String[] args) throws Exception{
        Connection conn = getConn();
        DatabaseMetaData metaData = conn.getMetaData();
        // 2.resultSet 
        ResultSet resultSet = metaData.getTables(null, null, "table_name", new String[]{"TABLE"});
        System.out.println("是否存在:" + resultSet.next());
    }
}

 错误查询方法: 



1.url
  没有设置nullCatalogMeansCurrent=true参数
2.resultSet
  metaData.getTables(null, null, "table_name", new String[]{"TABLE"});
  第一个参数未设置指定数据库名称.

jdbc就会在jdbc:mysql://localhost:3306/下扫描所有数据库是否存在table_name表

-----------------------------------------------------------------------------------------------

发现问题来源:

 springboot2.1.x 集成elastic-job不会自动创建JOB_EXECUTION_LOG,JOB_STATUS_TRACE_LOG表。

  (因为其他库存在这两张表)

分析:

  springboot2.1.x 集成mysql-connector-java为8.0.x版本,

  弃用com.mysql.jdbc.Driver,将会加载com.mysql.cj.jdbc.Driver驱动

elastic-job源码-->JobEventRdbStorage类中createJobExecutionTableAndIndexIfNeeded方法:

private void createJobExecutionTableAndIndexIfNeeded(final Connection conn) 
    throws SQLException {
    DatabaseMetaData dbMetaData = conn.getMetaData();
    try (ResultSet resultSet = 
// 说明:第一个参数并没有指定数据库名,根据上面的说明必须在连接jdbcurl处添加nullCatalogMeansCurrent=true参数
dbMetaData.getTables(null, null, TABLE_JOB_EXECUTION_LOG, new String[]{"TABLE"})) {
        // 查询表是否存在
        if (!resultSet.next()) {
            createJobExecutionTable(conn);
        }
    }
}

结论:

elastic-job会查询表JOB_EXECUTION_LOG,JOB_STATUS_TRACE_LOG是否存在,如果在其他库中存在,
则不会创建,所以当其他库中存在时,url必须加上nullCatalogMeansCurrent=true参数,
公司项目正是因为没有设置nullCatalogMeansCurrent参数,其他库存在该表,才导致不可以自动创建。

帮助博客:

 Mybatis Generator使用com.mysql.cj.jdbc.Driver遇到的问题 : 
        https://www.cnblogs.com/boboooo/p/9100991.html

 JDBC如何判断数据库的表是否存在 :
        https://blog.youkuaiyun.com/naruto0025/article/details/74201730

 

    

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值