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:\>
广告

© . All rights reserved.