Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, how to change current database to another?

Tags:

I have a Java program connection to a MySQL database, how can I change the current database to a different one on the same connection?

I connect to MySQL like this:

DriverManager.getConnection("jdbc:mysql://"+server+"/",log,pass);

After some operations I want to connect to a different mysql database on the same connection. How can I do that?

I tried to use:

Statement stat= con.createStatement();
ResultSet r=stat.executeQuery("use mysql"); 

But that does not change the database to be used.

like image 672
Krzysztof Avatar asked Nov 17 '12 18:11

Krzysztof


2 Answers

As described in the MySQL documentation you need to use Connection.setCatalog() to switch to another database. It also explicitly says that you should not execute a USE <databasename> to switch.

The reason for this warning is that JDBC is a generic interface to databases and therefor provides methods for most common tasks, including switching catalogs (or databases as they are in MySQL). The JDBC specification/javadoc also explicitly says that people should use the API over database specific commands (if both are available). There are several reasons for this: 1) it promotes database-independent code, and 2) the driver might do additional things internally in response to one of the API methods. Using database specific commands might cause the driver to misbehave because its internal state does not match the database state.

A call to setCatalog(String) will not affect existing statements, as specified in the JDBC API documentation:

Calling setCatalog has no effect on previously created or prepared Statement objects. It is implementation defined whether a DBMS prepare operation takes place immediately when the Connection method prepareStatement or prepareCall is invoked. For maximum portability, setCatalog should be called before a Statement is created or prepared.

like image 173
Mark Rotteveel Avatar answered Sep 29 '22 00:09

Mark Rotteveel


You can prefix the database name on your table names like this.

For example: db1 has table1 and db2 has table2

select * from db1.table1, db2.table2;

This will allow you to do cross database queries

like image 20
Subin Sebastian Avatar answered Sep 29 '22 01:09

Subin Sebastian