JDBC - 選擇資料庫



本章提供使用 JDBC 應用程式選擇資料庫的示例。在執行以下示例之前,請確保已準備好以下內容:

  • 要執行以下示例,您需要將使用者名稱密碼替換為您實際的使用者名稱和密碼。

  • 您的 MySQL 或您正在使用的任何資料庫都已啟動並正在執行。

所需步驟

使用 JDBC 應用程式建立新資料庫需要以下步驟:

  • 匯入包 - 需要包含資料庫程式設計所需的 JDBC 類所在的包。大多數情況下,使用import java.sql.*就足夠了。

  • 開啟連線 - 需要使用DriverManager.getConnection()方法建立一個 Connection 物件,該物件表示與選定資料庫的物理連線。

    資料庫的選擇是在您準備資料庫 URL 時進行的。以下示例將與STUDENTS資料庫建立連線。

  • 清理環境 - try with resources 自動關閉資源。

示例:選擇資料庫

在此示例中,我們有三個靜態字串,包含資料庫連線 URL、使用者名稱、密碼。現在使用 DriverManager.getConnection() 方法,我們已準備了一個數據庫連線。連線準備就緒後,我們列印了成功訊息。

如果在連線到資料庫時出現任何異常,catch 塊將處理 SQLException 並列印堆疊跟蹤。

將以下示例複製並貼上到 JDBCExample.java 中,編譯並執行如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {
   static final String DB_URL = "jdbc:mysql:///TUTORIALSPOINT";
   static final String USER = "guest";
   static final String PASS = "guest123";

   public static void main(String[] args) {
      System.out.println("Connecting to a selected database...");
      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);) {		      
         System.out.println("Connected database successfully...");  
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

輸出

現在讓我們按如下方式編譯以上示例:

C:\>javac JDBCExample.java
C:\>

當您執行JDBCExample時,它會產生以下結果:

C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
C:\>

我們已經瞭解瞭如何連線到資料庫,在下面的示例中,我們將從連線的資料庫的表中獲取資料。

示例:從選定資料庫的表中獲取記錄

在此示例中,我們有三個靜態字串,包含資料庫連線 URL、使用者名稱、密碼。現在使用 DriverManager.getConnection() 方法,我們已準備了一個數據庫連線。連線準備就緒後,我們使用 connection.createStatement() 方法建立了一個 Statement 物件。

首先使用“SHOW DATABASES”命令顯示資料庫列表。然後,SQL 命令“USE TUTORIALSPOINT”用於選擇資料庫。然後,在表“EMPLOYEES”上發出 SQL 查詢,以證明已使用所述資料庫。

如果在建立資料庫時出現任何異常,catch 塊將處理 SQLException 並列印堆疊跟蹤。

將以下示例複製並貼上到 JDBCExample.java 中,編譯並執行如下:

import java.sql.*;
// This class demonstrates use of selecting a database.
public class JDBCExample {
   static final String DB_URL = "jdbc:mysql:///";
   static final String USER = "guest";
   static final String PASS = "guest123";

   public static void main(String[] args) {

      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);) {		      
         System.out.println("Connected database successfully...");
         Statement stmt = conn.createStatement();
         ResultSet rs1 = stmt.executeQuery("SHOW DATABASES");
         System.out.println("DATABASES");
         System.out.println("-------------------------------------------");
         while( rs1.next()){
            System.out.println(rs1.getString(1));
         }

         System.out.println("-------------------------------------------------------");
         // The line below SELECTS a database TUTORIALSPOINT   
         stmt.executeUpdate("use TUTORIALSPOINT");
         ResultSet rs2 = stmt.executeQuery("select * from employees");
         System.out.println("Id of employees");
         while (rs2.next()){
            System.out.println("id= " + rs2.getInt("id"));
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

輸出

現在讓我們按如下方式編譯以上示例:

C:\>javac JDBCExample.java
C:\>

當您執行JDBCExample時,它會產生以下結果:

C:\>java JDBCExample
Connected database successfully..
DATABASES
-------------------------------------
information_schema
mysql
performance_schema
sample_db1
students
sys
tutorialspoint
tutorialspoint_copy
world
-------------------------------------------------------
Id of employees
id= 1
id= 2
id= 3
id= 4
id= 7
id= 8
id= 21
id= 22
id= 25
id= 26
id= 34
id= 35
id= 36
id= 37

C:\>

讓我們在下面的示例中探索其他命令,例如顯示選定資料庫中的表。

示例:獲取選定資料庫的當前資料庫和表名

在此示例中,我們有三個靜態字串,包含資料庫連線 URL、使用者名稱、密碼。現在使用 DriverManager.getConnection() 方法,我們已準備了一個數據庫連線。連線準備就緒後,我們使用 connection.createStatement() 方法建立了一個 Statement 物件。

SQL 命令“USE TUTORIALSPOINT”用於選擇資料庫。現在使用“SELECT DATABASE()”,我們正在列印當前選定的資料庫。然後,發出 SQL 查詢“SHOW TABLES”,以顯示連線資料庫的表。

如果在建立資料庫時出現任何異常,catch 塊將處理 SQLException 並列印堆疊跟蹤。

將以下示例複製並貼上到 JDBCExample.java 中,編譯並執行如下:

import java.sql.*;

// This class demonstrates use of SELECT DATABASE() command and SHOW TABLES        
public class JDBCExample {

   static final String DB_URL = "jdbc:mysql:///";
   static final String USER = "root";
   static final String PASS = "guest123";

   public static void main(String args[]) {
      // TODO code application logic here
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);) {		      
         System.out.println("Connected database successfully...");

         Statement stmt = conn.createStatement();
         // This statement will make TUTORIALSPOINT as the current database.
         stmt.executeUpdate("use TUTORIALSPOINT");

         // This will tell us which is the selected database
         ResultSet rs1 = stmt.executeQuery("SELECT DATABASE()");

         while( rs1.next()){
            System.out.println("Current database: " + rs1.getString(1));
         }

         ResultSet rs2 = stmt.executeQuery("SHOW TABLES");
         System.out.println("List of tables in current database TUTORIALSPOINT");
         System.out.println("---------------------------------------------------");

         while(rs2.next()){
            System.out.println( rs2.getString(1));
         }

      }catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

輸出

現在讓我們按如下方式編譯以上示例:

C:\>javac JDBCExample.java
C:\>

當您執行JDBCExample時,它會產生以下結果:

C:\>java JDBCExample
Connected database successfully...
Current database: tutorialspoint
List of tables in current database TUTORIALSPOINT
---------------------------------------------------
employees
jdbc_blob_clob
officers
students

C:\>
廣告