How can I verify if a certain MySQL database exists from Java?

2

I want to verify if my database exists before continuing with the execution of my program, but I do not know where to start, because I have looked at some examples and nothing has worked for me.

This is the query that you want to throw:

"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'Data_base'"
    
asked by Angel Montes de Oca 16.10.2017 в 20:43
source

2 answers

3

After investing and a few tests I found the solution, create this function to verify if it exists, using the jdbc driver:

public boolean dbExists(String puerto, String db, String pass) {
        boolean exist = false;
        try {
            Connection conn = null;
            Statement st = null;
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:" + puerto + "/" + db, "root", pass);
            st = conn.createStatement();
            String sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" + db + "'";
            ResultSet rs = st.executeQuery(sql);

            if (rs.next()) {
                //JOptionPane.showMessageDialog(main, "La base de datos existe.");
                exist = true;
            }
        } catch (ClassNotFoundException ex) {

        } catch (SQLException ex) {
            //JOptionPane.showMessageDialog(main, "La base de datos no existe.");
            exist = false;
        }
        return exist;
    }

I hope it helps you in case you are looking for something similar

    
answered by 16.10.2017 / 23:41
source
0

You can use the show databases query with like

String sql="show databases like '" + db + "'";

and check if the query returns a result.

    
answered by 19.10.2017 в 07:23