版权声明:取之网络,分享之网络. https://blog.csdn.net/qq_37751454/article/details/90737740
驱动: 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());
}
}
错误查询方法:
当:2.resultSet
metaData.getTables(null, null, "table_name", new String[]{"TABLE"});
第一个参数未设置指定数据库名称,
同时1.url没有设置nullCatalogMeansCurrent=true参数
jdbc就会在jdbc:mysql://101.132.44.225: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();
// 说明:第一个参数并没有指定数据库名,根据上面的必须在连接jdbcurl处添加
// nullCatalogMeansCurrent=true参数
try (ResultSet resultSet =
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.csdn.net/naruto0025/article/details/74201730