根据Mysql JDBC基本操作,我们大概可以总结出JDBC的API。
- Driver :jdbc驱动
- DriverManager:驱动注册类,创建Connection连接
- Connection:物理连接
- Statement、PreparedStatement:sql语句
- ResultSet:结果集
以下是Mysql JDBC 的基本操作流程。
- 准备数据库连接基础信息
- 注册JDBC驱动
- 打开创建数据库连接
- 执行数据库CRUD操作
- 处理结果集
- 关闭连接
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQLDemo {
// 1. 数据库基础连接信息
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test";
static final String USER = "root";
static final String PASS = "2652693155";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// 2. 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 3. 打开链接
System.out.println("连接数据库...");
conn = (Connection)DriverManager.getConnection(DB_URL,USER,PASS);
// 4. 执行数据库CRUD
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// 5. 展开处理结果集
while(rs.next()){
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 站点名称: " + name);
System.out.print(", 站点 URL: " + url);
System.out.print("\n");
}
// 6. 完成后关闭数据库连接
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}