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.
Does
conn.setCatalog("STUDENTS")set the current database to databaseSTUDENTS?If I have switched the current database to
STUDENTS, why does runningst.executeUpdate("CREATE TABLE student")throwjava.sql.SQLException: No database selected?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...");
}