首頁  >  文章  >  Java  >  java判斷資料庫是否存在

java判斷資料庫是否存在

尚
原創
2019-12-28 10:42:463137瀏覽

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語法:

String sql = "SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name=\"" + database + "\"";

更多java知識請關注java基礎教學欄。

以上是java判斷資料庫是否存在的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn