java jdbc查询式建表

在项目重复部署的过程中,初始化表的再次创建会引发错误,这就产生了查询式建表的需求。

如果表已经存在,那就不创建;如果不存在,就新建这张表。

确定表是否已经存在的接口:

 public boolean HaveTables(String tablename) throws SQLException {
		 //ConnectionPool pool = ConnectionPool.getInstance();
	    // Connection conn = null;
		 Connection  conn = ConnectionPool.getConnection();
		 Statement stmt= conn.createStatement();
		 ResultSet rs = conn.getMetaData().getTables(null, null, tablename, null);
		 if (rs.next()) {  
			 rs.close();
			 stmt.close();
			 conn.close();
             return true;  
       }else {  
    	   rs.close();
			 stmt.close();
			 conn.close();
             return false;  
       }  
	 }

参数是想要新建表的表名,要注意不同环境下是不一样的,Linux环境下是大小写敏感的。Windows大小写不敏感。

大小写敏感,可以用 或 查询 ,大小写都查一次。

返回值为false,就新建这张表。获取连接方式见 连接池配置文章。

你可能感兴趣的:(java,mysql)