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
Release: 2023-08-29 19:09:02
forward
1223 people have browsed it

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

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

Syntax

Use DatabaseName;
Copy after login

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.

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......");
   }
}
Copy after login

Output

Connection established......
Database changed......
Copy after login

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");
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template