翻譯自:JDBC MySQL Connection Tutorialjava
Java Database Connectivity (JDBC) 是一個基於Java的數據訪問技術,它定義了用戶入戶訪問一個數據庫。它提供了一組在數據庫查詢、修改數據的方法。JDBC類包含在java.sql
和javax.sql
包中。mysql
按照以下步驟創建一個JDBC開發環境,並在這個環境上運行JDBC MYSQL示例程序。linux
確認你已經安裝了Java SE。安裝參考 Windows Ubuntusql
MySQL安裝參考連接ubuntu
JDBC API幾乎包含了任意一個數據庫的可獨立工做的接口。每一種數據庫都須要一個特有的驅動,該驅動實現了JDBC API。windows
JDBC數據庫鏈接器提供了訪問數據庫的入口,爲了能經過JDBC訪問數據庫,咱們須要數據庫廠商提供的JDBC驅動。這個驅動一般是以jar或zip文件或其它有效形式同數據庫產品一塊兒在官網發佈的。這些文件必須放在classpath中(後面的「在Eclipse中配置JDBC驅動」步驟中會講到),不然會出現class-not-found-exceptions
,表示未在classpath中發現驅動。服務器
此示例使用的database爲"jdbcdb",其中包含下面的表;app
代碼:eclipse
sudo service mysql mysql -u [此處username] -p [此處password] create database jdbcdb; use jdbcdb;
Field | Type | Key | Extra |
---|---|---|---|
dept_id | int | Primary Key | auto_increment |
dept_name | varchar(50) | ||
location | varchar(50) |
代碼:
CREATE TABLE Department ( dept_id int PRIMARY KEY AUTO_INCREMENT, dept_name varchar(50), location varchar(50) );
Field | Type | Key | Extra |
---|---|---|---|
emp_id | int | Primary Key | auto_increment |
emp_name | varchar(50) | ||
dob | date | ||
salary | double | ||
dept_id | int | Foreign key references department(dept_id) |
代碼:
CREATE TABLE Employee ( emp_id int PRIMARY KEY AUTO_increment, emp_name varchar(50), dob date, salary double, dept_id int, FOREIGN KEY (dept_id) REFERENCES Department(dept_id) );
最後,咱們分別向兩個表插入一些數據,好比:
insert into Department value(1, 'Finace', 'Service Building'); insert into Department value(2, 'Technology', 'Center Building'); insert into Employee value(1, 'wcb', '2088-08-08', 2888.8, 2);
咱們寫一個類 (JDBCMySQLConnection) 來定義數據庫鏈接的配置聲明和方法,使JDBC鏈接到MySQL數據庫。
你須要從java.sql.*包中導入須要的類/接口,它們是Java Application和數據庫之間的橋樑。
Java MySQL驅動(com.mysql.jdbc.Driver)可從下載的Java MySQL鏈接器的JAR文件中得到。這個鏈接器JAR文件要被包含到工程的classpath,後面的」在Eclipse中配置JDBC驅動「中會講。
語句Class.forName("com.mysql.jdbc.driver")
會使MySQL Java驅動被加載到內存。
在下面的代碼中,咱們建立一個靜態字符串常量做爲參數傳遞給Class.forName
方法
public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver"; Class.forName(DRIVER_CLASS);
咱們經過DriverManager
類的getConnection()
方法獲取從Java到MySQL的鏈接對象,此方法須要JDBC MySQL鏈接URL字符串,MySQL數據庫的用戶名和密碼做爲參數。在此示例中,咱們已將這些參數做爲常量傳遞給getConnection()
方法。
public static final String URL = "jdbc:mysql://localhost/jdbcdb"; public static final String USER = "YOUR_DATABASE_USERNAME"; public static final String PASSWORD = "YOUR_DATABASE_PASSWORD"; . . . . . . Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
jdbc:<DBMS>://<HOSTNAME>:<PORT_NUMBER>/YOUR_DATABASE_NAME
例如,Java-MySQL鏈接URL字符串:
jdbc:mysql://localhost:3306/jdbcdb
其中,
爲了完成上面的步驟,新建一個類JDBCMySQLConnection
,並放在包com.theopentutorials.jdbc.db
中,而後複製下面的代碼:
package com.theopentutorials.jdbc.db; //Step 1: Use interfaces from java.sql package import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JDBCMySQLConnection { //static reference to itself private static JDBCMySQLConnection instance = new JDBCMySQLConnection(); public static final String URL = "jdbc:mysql://localhost/jdbcdb"; public static final String USER = "YOUR_DATABASE_USERNAME"; public static final String PASSWORD = "YOUR_DATABASE_PASSWORD"; public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver"; //private constructor private JDBCMySQLConnection() { try { //Step 2: Load MySQL Java driver Class.forName(DRIVER_CLASS); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private Connection createConnection() { Connection connection = null; try { //Step 3: Establish Java MySQL connection connection = DriverManager.getConnection(URL, USER, PASSWORD); } catch (SQLException e) { System.out.println("ERROR: Unable to Connect to Database."); } return connection; } public static Connection getConnection() { return instance.createConnection(); } }
咱們寫一個類Employee,其屬性爲數據庫中Employee表的屬性。
例如,爲了查詢Employee表,咱們用下面代碼實現Employee類;
package com.theopentutorials.jdbc.to; import java.util.Date; public class Employee { private int empId; private String empName; private Date dob; private double salary; private int deptId; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public void setDeptId(int deptId) { this.deptId = deptId; } public int getDeptId() { return deptId; } //toString() @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + ", dob=" + dob + ", salary=" + salary + ", deptId=" + deptId + "]"; } }
咱們寫一個 「JDBCMySQLDemo」 類放在「com.theopentutorials.jdbc.main」 包中,來測試JDBC MySQL鏈接並執行一個簡單的查詢語句。
package com.theopentutorials.jdbc.main; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.theopentutorials.jdbc.db.JDBCMySQLConnection; import com.theopentutorials.jdbc.to.Employee; public class JDBCMySQLDemo { public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the EmployeeID:"); int employeeId; try { employeeId = Integer.parseInt(br.readLine()); //21行 JDBCMySQLDemo demo = new JDBCMySQLDemo(); Employee employee = demo.getEmployee(employeeId); //23行 System.out.println(employee); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public Employee getEmployee(int employeeId) { ResultSet rs = null; Connection connection = null; Statement statement = null; Employee employee = null; String query = "SELECT * FROM Employee WHERE emp_id=" + employeeId; //38行 try { connection = JDBCMySQLConnection.getConnection(); statement = connection.createStatement(); //41行 rs = statement.executeQuery(query); //42行 if (rs.next()) { //44行 employee = new Employee(); employee.setEmpId(rs.getInt("emp_id")); employee.setEmpName(rs.getString("emp_name")); employee.setDob(rs.getDate("dob")); employee.setSalary(rs.getDouble("salary")); employee.setDeptId((rs.getInt("dept_id"))); } //51行 } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); //57行 } catch (SQLException e) { e.printStackTrace(); } } } return employee; } }
這個JDBC MySQL示例獲得用戶輸入的employee ID,在數據庫中找到這個employee而且利用標準輸出顯示詳情。
這段程序步驟以下:
若是你此時運行JDBCMySQLDemo
類會產生以下異常:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
你須要將以前下載好的Java MySQL Connector JAR文件添加到工程的classpath中。
右擊工程名(JDBCMySQLSample
) ->Properties
-> Buildpath
-> Libraries
-> Add External JAR
而後選擇 「mysql-connector-java-5.1.14-bin.jar」 JAR 文件.
運行JDBCMySQLDemo類,將獲得以下的輸出結果:
此示例項目的完整的文件結構以下所示: