基础知识点:
Class.forName("com.mysql.cj.jdbc.Driver")
:Class.forName()
要求JVM查找并加载指定的类- 此段代码: 加载驱动程序
useUnicode=true&characterEncoding=utf-8
:- 添加在URL末尾,避免乱码问题
Connection接口:
- 与指定数据库的连接(会话),通过这个连接的上下文,SQL语句可以被执行,也可以作为返回值
- 用户获取数据库的连接:
conn = DriverManager.getConnection(URL, USER, PASSWORD);
- 创建PreparedStatement对象,并传入参数化SQL语句:
ps = conn.prepareStatement(sql)
DriverManager对象:
- 管理JDBC驱动的基础的服务
getConnection()
: 用于与数据库建立连接,返回类型是Connection接口
PreparedStatement接口:
- 用于执行SQL语句查询的接口
- 会对SQL语句进行预编译处理,并且存储在此对象中
- 预编编译的SQL语句会在查询中被重用,效率高于多次Statement对象的查询
- 能够使用动态化参数的查询: 使用
?
占位符 - 使用给定的对象设置参数的值:
ps.setObject(i + 1, objects[i])
- 执行SQL更新语句:
ps.executeUpdate() // 返回更新的条数
- 执行SQL查询语句:
rs = ps.executeQuery() // 返回ResultSet对象
ResultSet接口:
- 用于表示数据查询的结果
- 一般作为查询语句的返回值
- 从ResultSet中取得所有数据:
while(rs.next()) { // 当rs还有下一个数据时
// 从rs中取得不同属性,并创建新对象后存入容器
list.add(new Book(rs.getInt(1), rs.getString(2), rs.getDouble(3), rs.getString(4), rs.getDate(5)));
}
JDBC实现步骤
创建基础的Dao对象:
- 加载驱动程序:
Class.forName("com.mysql.cj.jdbc.Driver")
- 建立数据库连接:
conn = DriverManager.getConnection(URL, USER, PASSWORD)
- 传入sql语句:
ps = conn.prepareStatement(sql)
- 返回执行更新/查询的结果:
ps.executeUpdate() / ps.executeQuery()
- 关闭数据库连接:
conn.close() / ps.close() / rs.close()
- 加载驱动程序:
创建实体Dao对象
- 继承基础Dao对象,根据具体业务进行封装
代码示例:
public class BaseDao {
public static final String URL = "jdbc:mysql://localhost:3306/booksys?useUnicode=true&characterEncoding=utf-8";
public static final String USER = "root";
public static final String PASSWORD = "chenyu123";
private Connection conn = null; //连接对象
private PreparedStatement ps = null; //SQL语句执行对象
private ResultSet rs = null; //
//获得连接
private void getConnection() {
try {
//加载驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
//获得数据库连接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
//更新操作---增、改、删
public int executeUpdate(String sql, Object...objects) {
try {
this.getConnection();
//创建preparedStatement对象,用于传入参数化SQL语句
ps = conn.prepareStatement(sql);
if(objects != null) { // 有参数传入
for(int i = 0; i < objects.length; i++) {
ps.setObject(i + 1, objects[i]);
}
}
return ps.executeUpdate(); // 返回更新的条数,0代表没有更新
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.close();
}
return -1;
}
//查询操作
public ResultSet executeQuery(String sql, Object...objects) {
try {
this.getConnection();
ps = conn.prepareStatement(sql);
if(objects != null) {
for(int i = 0; i < objects.length; i++) {
ps.setObject(i + 1, objects[i]);
}
}
return rs = ps.executeQuery(); // 返回ResultSet对象
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//关闭连接
public void close() {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public class BookDao extends BaseDao{
//查询所有数据
public List<Book> getAll() {
List<Book> list = new ArrayList<Book> ();
String sql = "select * from book";
try {
ResultSet rs = this.executeQuery(sql);
while(rs.next()) { // 当rs还有下一个数据时
// 从rs中取得不同属性,并创建新对象后存入容器
list.add(new Book(rs.getInt(1), rs.getString(2), rs.getDouble(3), rs.getString(4), rs.getDate(5)));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.close();
}
return list;
}
//添加书籍
public int add(Book b) {
// 使用占位符写SQL语句
String sql = "insert into book(name, price,author, pubDate) value(?, ?, ?, ?)";
// 使用动态参数化的特性,传入所添加的书籍的属性
return this.executeUpdate(sql, b.getName(), b.getPrice(), b.getAuthor(),
new SimpleDateFormat("yyyy-MM-dd").format(b.getPubDate()));
}
//根据ID查找对应的书籍
public Book getById(int id) {
// 便于其他操作的实现
String sql = "select * from book where id = ?";
try {
ResultSet rs = this.executeQuery(sql, id);
if(rs.next()) {
return new Book(rs.getInt(1), rs.getString(2), rs.getDouble(3), rs.getString(4), rs.getDate(5));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.close();
}
return null;
}
//修改书籍信息
public int update(Book b) {
String sql = "update book set name = ?, price = ?, author = ?, pubDate = ? where id = ?";
return this.executeUpdate(sql, b.getName(), b.getPrice(), b.getAuthor(),
new SimpleDateFormat("yyyy-MM-dd").format(b.getPubDate()), b.getId());
}
//删除书籍信息
public int delete(int id) {
String sql = "delete from book where id = ?";
return this.executeUpdate(sql, id);
}
}