Checking existence of database and a table in it: `java.sql.SQLException: No database selected`

Viewed 81

When using jdbc for mysql, I want to first check if an database and a table in it both exist, before inserting some tuple into the table. The following code is my attempt.

  1. Does conn.setCatalog("STUDENTS") set the current database to database STUDENTS?

  2. If I have switched the current database to STUDENTS, why does running st.executeUpdate("CREATE TABLE student") throw java.sql.SQLException: No database selected?

  3. Are my ways of checking existence of database and table correct? Are there better ways?

Thanks.

Class.forName("com.mysql.jdbc.Driver");

//Open a connection                                                                                                                                                    
System.out.println("Connecting to database...");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);                                      

//Execute a query                                                                                                                                                      
Statement st = conn.createStatement();

// check existence of database  STUDENTS                                                                                                                                        
DatabaseMetaData dbm = conn.getMetaData();
ResultSet databases = dbm.getCatalogs();
boolean hasDB = false;
while (databases.next()){
    String databaseName = databases.getString(1);
    if (databaseName.equals("STUDENTS")){
        hasDB = true;
        break;}
}
if (!hasDB){
    st.executeUpdate("CREATE DATABASE STUDENTS");
    System.out.println("Database created successfully...");
}
conn.setCatalog("STUDENTS"); // Can this set the current database to STUDENTS?

// Check existence of table `student` in database `STUDENTS`
ResultSet tables = dbm.getTables(null, null, "student", null);
if (! tables.next()){
    st.executeUpdate("CREATE TABLE student"); // java.sql.SQLException: No database selected
    System.out.println("Table created successfully...");
}
1 Answers
Related