以前使用过JDBC,但没有系统地学过。这次因为需要,所以想重新学一遍JDBC。故参照JDBC教程(http://www.yiibai.com/jdbc/jdbc_quick_guide.html),记录下JDBC的学习过程。
以连接MySQL数据库为例
需要Jar包:
mysql-connector-java-X.X.X-bin.jar (X.X.X为jar包版本号)
注册JDBC驱动程序:
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; Class.forName(JDBC_DRIVER);
建立一个连接:
static final String DB_URL = "jdbc:mysql://localhost/test"; static final String USER = "root"; static final String PASS = "123456"; Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
执行一个查询操作:
Statement stmt = conn.createStatement(); String sql = "SELECT * FROM user"; ResultSet rs = stmt.executeQuery(sql);
从结果集中提取数据:
while (rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); }
清理环境资源:
rs.close(); stmt.close(); conn.close();
完整示例:
package com.shirley;
import java.sql.*;
public class Main {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test?useSSL=true";
static final String USER = "root";
static final String PASSWORD = "123456";
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null){
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try{
if (conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
运行结果: