阅读(3657) (38)

JDBC 选择数据库

2017-01-09 19:11:18 更新

JDBC教程 - JDBC选择数据库


以下代码显示如何使用JDBC连接URL选择数据库。

该代码对JDBC连接URL中的数据库名称进行了硬编码,如下所示。

jdbc:mysql://localhost/STUDENTS

例子

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

public class Main {
  static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

  static final String USER = "username";
  static final String PASS = "password";

  public static void main(String[] args) throws Exception {
    Connection conn = null;
    Statement stmt = null;

    Class.forName(JDBC_DRIVER);
    conn = DriverManager.getConnection(DB_URL, USER, PASS);

    stmt.close();
    conn.close();
  }
}