目录
- JDBC 脑图
- 附:JDBC 应用案例、异常处理、批处理
JDBC
附
- JDBC 应用案例
// 应用
import java.sql.*;
public class JdbcTest {
// JDBC 驱动器名称 和数据库地址
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
//数据库的名称为 EXAMPLE
static final String DB_URL = "jdbc:mysql://localhost/EXAMPLE";
// 数据库用户和密码
static final String USER = "root";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//注册 JDBC 驱动程序
Class.forName("com.mysql.jdbc.Driver");
//打开连接
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//执行查询
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM Students";
ResultSet rs = stmt.executeQuery(sql);
//得到和处理结果集
while(rs.next()){
//检索
int id = rs.getInt("id");
int age = rs.getInt("age");
String name = rs.getString("name");
//显示
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", Name: " + name);
System.out.println();
}
//清理环境
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!");
}
}
- 异常处理
// 常见
java.sql.SQLException;
方法 | 描述 |
---|---|
getErrorCode() | 获取此 SQLException 对象的特定于供应商的异常代码 |
getNextException() | 通过 setNextException(SQLException ex) 获取链接到此 SQLException 对象的异常 |
getSQLState() | 获取此 SQLException 对象的 SQLState。对于 JDBC 驱动程序的错误,没有有用的信息从该方法返回。对于一个数据库错误,则返回五位 XOPEN SQLSTATE 代码。这种方法可以返回 null |
iterator() | 返回在链接的 SQLExceptions 上进行迭代的迭代器 |
setNextException(SQLException ex) | 将 SQLException 对象添加到链接的末尾 |
- 批处理
// 批处理
// 创建 statement 对象
Statement stmt = conn.createStatement();
// 关闭自动提交
conn.setAutoCommit(false);
// 创建 SQL 语句
String SQL = "INSERT INTO Students (id, name, age) VALUES(6,'Mike', 21)";
// 将 SQL 语句添加到批处理中
stmt.addBatch(SQL);
// 创建更多的 SQL 语句
String SQL = "INSERT INTO Students (id, name, age) VALUES(7, 'Angle', 23)";
// 将 SQL 语句添加到 批处理中
stmt.addBatch(SQL);
// 创建整数数组记录更新情况
int[] count = stmt.executeBatch();
//提交更改
conn.commit();