首頁  >  文章  >  資料庫  >  如何使用 JDBC API 選擇或轉移到 MySQL 中的另一個資料庫?

如何使用 JDBC API 選擇或轉移到 MySQL 中的另一個資料庫?

PHPz
PHPz轉載
2023-08-29 19:09:021116瀏覽

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

一般來說,您可以使用 USE 查詢來變更 MySQL 中的目前資料庫。

語法

Use DatabaseName;

要使用JDBC API 更改目前資料庫,您需要:

  • 註冊驅動程式 :使用DriverManager類別的registerDriver()方法註冊驅動程式類別。將驅動程式類別名稱作為參數傳遞給它。

  • 建立連線:使用 DriverManager 類別的 getConnection() 方法連接資料庫。將 URL(字串)、使用者名稱(字串)、密碼(字串)作為參數傳遞給它。

  • 建立語句:使用Connection介面的createStatement()方法。

  • 執行查詢:使用Statement介面的execute()方法執行查詢。 p>

範例

以下JDBC 程式與MySQL 建立連線並選擇名為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......");
   }
}

輸出

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

除此之外,您還可以透過在URL 末尾傳遞資料庫名稱來選擇/切換到MySQL 中所需的資料庫,如下所示-

//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");

以上是如何使用 JDBC API 選擇或轉移到 MySQL 中的另一個資料庫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除