Java Mysql 简明教程

Java & MySQL - Select Database Example

此章节提供了一个有关如何使用 JDBC 应用选择数据库的示例。在执行以下示例之前,请确保您已经准备就绪:

This chapter provides an example on how to select a Database using JDBC application. Before executing the following example, make sure you have the following in place −

  1. To execute the following example you need to replace the username and password with your actual user name and password.

  2. Your MySQL database you are using, is up and running.

Required Steps

创建新的数据库使用 JDBC 应用程序需要执行以下步骤:

The following steps are required to create a new Database using JDBC application −

  1. Import the packages − Requires that you include the packages containing the JDBC classes needed for the database programming. Most often, using import java.sql.* will suffice.

  2. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a selected database.

  3. Selection of database is made while you prepare database URL. Following example would make connection with STUDENTS database.

  4. Clean up the environment − try with resources automatically closes the resources.

Sample Code

复制并粘贴以下示例到 JDBCExample.java 中,并按照以下方式编译和运行:

Copy and paste the following example in JDBCExample.java, compile and run as follows −

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://localhost/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();
      }
   }
}

现在让我们如下编译上述示例:

Now let us compile the above example as follows −

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

运行 JDBCExample 时,将产生以下结果:

When you run JDBCExample, it produces the following result −

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