Home >Database >Mysql Tutorial >How to select or move to another database in MySQL using JDBC API?

How to select or move to another database in MySQL using JDBC API?

PHPz
PHPzforward
2023-08-29 19:09:021196browse

如何使用 JDBC API 选择或转移到 MySQL 中的另一个数据库?

Generally speaking, you can use USE queries to change the current database in MySQL.

Syntax

Use DatabaseName;

To use the JDBC API Change the current database, you need to:

  • Register Driver: Use the registerDriver() method of the DriverManager class to register the driver class. Pass it the driver class name as a parameter.

  • Establish a connection: Use the getConnection() method of the DriverManager class to connect to the database. Pass it URL (String), Username (String), Password (String) as parameters.

  • Create statement: Use the createStatement() method of the Connection interface.

  • Execute query: Use the execute() method of the Statement interface to execute the query. p>

Example

The following JDBC program establishes a 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......

except Additionally, you can select/switch to the desired database in MySQL by passing the database 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");

The above is the detailed content of How to select or move to another database in MySQL using JDBC API?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete