JDBC 是什么
Java DataBase Connectivity 的简称,是 Java 语言中用来规范客户端程序如何访问数据库的应用程序接口,提供了如查询和更新数据库中数据的方法。
为什么需要 JDBC
简化面对不同数据库的操作,操作数据库都在 JDBC API 上,使用不同的数据库,只要用不同数据库厂商提供的数据库驱动即可。
使用 JDBC 的基本步骤
- 导入数据库驱动包
- 加载数据库驱动程序
- 获取与数据库的连接
- 获取向数据库发送 SQL 语句的对象
- 执行 SQL 语句
- 关闭连接
以 MySQL 为例
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//获取与数据库的连接
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","username","password");
//获取向数据库发送 SQL 语句的对象
Statement statement=conn.createStatement();
//执行 SQL 语句
ResultSet resultSet=statement.executeQuery("select * from tablename");
//遍历结果集
while(resultSet.next()){
//处理数据
}
//关闭连接,后调用的要先关闭,需要先判断对象是否存在
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
主要对象及方法
Connection 对象
客户端与数据库所有的交互都是通过该对象完成的。
常用方法:
createStatement()创建执行 SQL 语句的 Statement 对象prepareStatement()创建向数据库发送预编译 SQL 语句的 PrepareStatement 对象prepareCall(sql)创建执行存储过程的 callableStatement 对象setAutoCommit(boolean autoCommit)设置事务自动提交commit()提交事务rollback()回滚事务
Statement 对象
Statement 对象用于向数据库发送 SQL 语句,对数据库的增删改查操作都是通过 Statement 对象向数据库发送 SQL 语句完成的。
常用方法:
executeQuery(String sql)查询executeUpdate(String sql)增删改execute(String sql)任何 SQL 语句都可以,但是目标不明确,很少用addBatch(String sql)把多条 SQL 语句放进同一批处理中executeBatch()向数据库发送一批 SQL 语句实行
ResultSet 对象
ResultSet 对象是 SQL 语句的执行结果,当 Statement 对象执行 executeQuery() 方法后,会返回一个 ResultSet 对象。
常用方法:
getObject(String columnName)获取任意类型的数据getString(String columnName)获取指定类型的数据- 以下为对结果集进行滚动查看的方法,即控制数据行的游标
next()previous()absolute(int row)beforeFirst()afterLast()
编写工具类
为了提到代码复用性,简化代码,可以将 JDBC 的基本操作封装到一个工具类中。