How to select or, shift to another database in MySQL using a JDBC API?

JDBCObject Oriented ProgrammingMySQLProgramming

In general, You can change the current database in MySQL using the USE query.

Syntax

Use DatabaseName;

To change the current database using JDBC API you need to:

  • Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.

  • Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.

  • Create Statement: Create a Statement object using the createStatement() method of the Connection interface.

  • Execute the Query: Execute the query using the execute() method of the Statement interface.

Example

Following JDBC program establishes connection with MySQL and selects the database named mydatabase -

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class ChangeDatabaseExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Create table Query
      String query = "USE mydatabase";
      //Executing the query
      stmt.execute(query);
      System.out.println("Database changed......");
   }
}

Output

Connection established......
Database changed......

In addition to this, you can also select/switch to required database in MySQL by passing its name at the end of the URL as shown below -

//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
raja
Published on 01-Apr-2019 14:08:24
Advertisements