最近使用Springjdbc+Mysql来开发一个项目,记录两个问题。java
判断数据库是否存在sql
方法1:使用原生Mysql语句,use database方式,并执行,根据执行结果是否出现异常来判断数据库是否存在,代码以下数据库
public boolean isDbExist(String dbName) { try { String sql = "USE "+dbName; jdbcTemplate.execute(sql); return true; } catch (Exception e) { System.out.println("数据库不存在"); return false; } }
方法2:使用创建数据库链接的方法来判断,也是根据是否出现异常,可是此方法若是是多数据源的话须要反复切换数据源,不是很方便code
public boolean isDbExist(String dbName) { Connection conn = null; try { conn = jdbcTemplate.getDataSource().getConnection(); return true; } catch (Exception e) { System.out.println("数据库不存在"); }finally{ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; }
2.判断数据库的某个表是否存在开发
方法比较常规,就是根据表名查询一下,看看是否有记录,有记录即表存在,不然不存在get
public boolean isTableExist(String tableName) { Connection conn = null; ResultSet rs = null; try { conn = jdbcTemplate.getDataSource().getConnection(); rs = null; DatabaseMetaData data = conn.getMetaData(); String[] types = {"TABLE"}; rs = data.getTables(null, null, tableName, types); if(rs.next()){ return true; } } catch (Exception e) { e.printStackTrace(); }finally{ try { rs.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; }