问题描述:

 DB_CONNECTION_URL = "jdbc:mysql://localHost:3306/test_DB";

When I debug the program an exception occurs that the test_DB does not exist. Is it possible to create the database when the query executes?

网友答案:

You would have to connect to the server, rather than the specific database:

DB_CONNECTION_URL = "jdbc:mysql://localHost:3306/";

And then use CREATE SCHEMA to add the database.

网友答案:

I don't know too much about jdbc, but usually you can connect without specifying a database at all, then check if it exists and execute a USE test_db if it does, create it if it does not.

Often you'll see simply CREATE DATABASE IF NOT EXISTS test_db... and then USE test_db (i.e. eliminate the need to explicitly check for existence)

网友答案:

According to your question, you must create the database called 'test_DB' after connecting the database with JDBC.

网友答案:

Before executing your query check if the database exist or not , do something like

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","root");
Statement st = con.createStatement();
        DatabaseMetaData meta = con.getMetaData();
        ResultSet rs = meta.getCatalogs();
        while (rs.next()) {
            String listofDatabases=rs.getString("TABLE_CAT");
            list.add(listofDatabases);
        }
        if(list.contains(database)){
        System.out.println("Database already exists");

if not write query to create database.. like

String database = DATABASENAME; // "nlshriraam";//bf.readLine();
st.executeUpdate("CREATE DATABASE "+database);

then execute your query..

相关阅读:
Top