java判断数据库是否存在

java数据库是否存在可以使用如“String sql="SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name=""+database+"“””语句判断。

java判断数据库是否存在

java判断数据库是否存在的代码:

public static boolean isExistDatabase(String database) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;// 数据库结果集
        try {
            conn = getConnection();
            stmt = conn.createStatement();
            String sql = "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name="" + database + """;
            System.out.println(sql);
            rs = stmt.executeQuery(sql);
            if (rs.next()) {
                if (rs.getInt(1) == 0) {
                    return false;
                } else {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            throw new TenantException(e.getMessage(), Status.INTERNAL_SERVER_ERROR);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                throw new TenantException("mysql关闭连接失败:" + e.getMessage(), Status.INTERNAL_SERVER_ERROR);
            }
        }
    }
只听到从山间传来架构君的声音:
岭树重遮千里目,江流曲似九回肠。有谁来对上联或下联?

关键SQL语法:

此代码由Java架构师必看网-架构君整理
String sql = "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name="" + database + """;

谢谢大家,希望帮助更多的人

本文来源,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/35847
0

发表评论