MySQL doesn't support the concept of schema. For MySQL, the schema is in fact the database. From MySQL Glossary:
schema
Conceptually, a schema is a set of interrelated database objects, such as tables, table columns, data types of the columns, indexes, foreign keys, and so on. (...)
Based on this answer from MySQL forums, you can't get the current database (or databases) through Connection#getSchema
method (which was added since Java 7 with JDBC 4) but using Connection#getCatalog
unless you use the latest JDBC jar driver:
The JDBC driver (because of legacy, mysql didn't call them "schemas" until 5.0, and JDBC didn't have a way to select schemas until JDBC4), calls databases "catalogs", so thus you have to call getCatalogs() to get the list of databases
I made a dirty quick to prove the italic sentence above (unless you use the latest JDBC jar driver). Using getCatalog()
worked using Java 6:
public class DirtyQuickTest {
private static final String url = "jdbc:mysql://localhost:7841/test";
private static final String user = "lmendozaj";
private static final String password = "s3cr3t"; //I won't show you my password
public static void main(String[] args) throws Exception {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
//commented since doesn't exists in Java 6
//System.out.println(con.getSchema());
System.out.println(con.getCatalog());
} finally {
con.close();
}
}
}
Output:
test
Then I executed the same code in Java 8 and uncommented the statement containing getSchema
using mysql-connector-java-5.1.31-bin.jar (currently the latest Java Connector Driver for MySQL). This was the output:
null
test
Which means they still don't support getSchema
method.
Related: