一、 JDBC的概念:
JDBC(Java Database Connectivity)java数据库链接,是SUN公司为了方便我们Java程序员使用Java程序操作各种数据库管理系统制定的一套标准(规范), 其中定义一些接口、抽象类和抽象方法,再由各个数据库管理系统厂商实现这些抽象方法,我们程序员只要学习一套JDBC规范就可以操作各种数据库管理系统。
JDBC也是一个注册商标。
二、 JDBC的入门案例/JDBC的开发流程:
1. 创建一个Java project/web project:JDBC
2. 添加链接数据库的jar包:Mysql的jar包。
步骤:
1) 在项目的根目录下创建一个存放jar包的文件夹:lib
2) 将MySQL的jar包复制到lib下。
3) 在MySQL的jar包上右键build path Add to build path,将jar文件加入到当前项目中,自动添加到Reference Libraries库中。
3. 创建项目需要的包:
1)Com.oop.entity:放置实体(和数据库向对应)
2)Com.oop.dao:放置DAO接口,(Data Access Object)数据访问对象,专门与数据库打交道的对象,其中会提供一些针对数据库的CRUD方法
3)com.oop.dao.impl:放置DAO实现类中实现DAO接口中定义的方法。
4)com.oop.service:放置service接口,业务/服务层,通常用于编写与项目相关的一些业务代码,向下会调用DAO层的方法,并返回给上一层(controller层,控制器层)
5)com.oop.service.impl:放置service实现类,实现service接口中定义的方法。
6)com.oop.controller:放置控制器层的类,由Servlet程序作为控制器。
7)com.oop.util:工具包,放置一些项目中需要使用的通用工具类。
8)com.oop.test:测试包,放置针对项目代码测试的一些测试类。
4. 在com.oop.dao.impl层编写JDBC的实现类: tb_dept表对应的实体类Dept
package com.oop.entity;
import java.io.Serializable;
/**
* 练习封装tb_dept表对应的实体类Dept 八种基本数据类型对应的有八种引用数据类型(包装数据类型),
* byte short int long loat double char boolean
* Byte Short Integer Long Float Double Character
* Boolean
*
*/
public class Dept implements Serializable {
private static final long serialVersionUID = 1L;
private Integer deptNo; // 部门编号
private String dName; // 部门名称
private String loc; // 部门所在地
//setter、getter方法的区域:
public void setDeptNo(Integer deptNo) {
this.deptNo = deptNo;
}
public Integer getDeptNo() {
return deptNo;
}
public void setDName(String dName) {
this.dName = dName;
}
public String getDName() {
return dName;
}
public void setLoc(String loc) {
this.loc = loc;
}
public String getloc() {
return loc;
}
//构造方法的区域:
//默认的构造方法,当手动写了一个带参的构造方法,默认的就会失效
public Dept() {
}
//有参的构造方法
public Dept(Integer deptNo) {
this.deptNo = deptNo;
}
public Dept(String dName,String loc) {
this.dName = dName;
this.loc = loc;
}
public String method1() {
return null;
}
//重写toString方法
@Override
public String toString() {
return "Dept [deptNo=" + deptNo + ", dName=" + dName + ", loc=" + loc + "]";
}
}
DeptDaoImpl实现类:
EmpDaoImpl实现类:
1) 加载(注册)驱动:指定需要链接的是哪种数据库管理系统
2) 获取与数据库链接:需要指定URL(jdbc:mysql://127.0.0.1:3306/数据库名)、user、password。
3) 通过获取到的与数据库的链接connection向数据库发送SQL语句,返回PreparedStatement接口实现类的对象。
4) 通过PreparedStatement接口实现类的对象调用与数据类型相关的各种setter方法对“占位符”赋值。
5) 再通过PreparedStatement接口实现类的对象调用executeQuery()、executeUpdate()方法执行查询、增删改操作,并返回ResultSet接口类型 、int的结果
6) 对结果进行处理。
7) 关闭打开的资源:connection、PreparedStatement、ResultSet。关闭资源的顺序应采用倒叙的方式来关闭:先开的后关,后开的先关
package com.oop.dao.impl;
import java.sql.*;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import com.oop.entity.Dept;
/**
* 针对Dept实体操作的Dao实现类:
* 其中会提供一些针对Dept实体对应的数据表tb_dept的CRUD方法。
*/
public class DeptDaoImpl {
Connection ct = null;
PreparedStatement pst = null;
ResultSet rs = null;
Dept dept = null;
/**
* 通过Id(deptNo)查询Dept对象的Dao层方法。
* @param deptNo:部门编号,作为查询的条件,返回查询到的Dept对象
* @return
*/
public Dept selectDeptById(Integer deptNo) {
try {
//1---加载(注册)驱动:指定需要链接的是哪种数据库管理系统
/*
* 用Class类直接调用forName(String className)方法
* 获取Driver类在Class中注册的对象,通过该对象可以利用“反射机制”获取到Driver类中的所有信息。
*/
Class.forName("com.mysql.jdbc.Driver");
//2---获取与数据库链接:需要指定URL(jdbc:mysql://127.0.0.1:3306/数据库名)、user、password。
//返回值需要用一个connection接口实现类的对象ct接收
ct = DriverManager.getConnection("jdbc:mysql://127.0.0.1/myschool39", "root", "root");
//3---通过获取到的与数据库的链接connection向数据库发送带参数(占位符‘?’)的SQL语句,返回PreparedStatement接口实现类的对象pst。
String sql = "SELECT * FROM tb_dept WHERE deptno = ?";
pst = ct.prepareStatement(sql);
//4、通过PreparedStatement接口实现类的对象pst调用与数据类型相关的各种setter方法对“占位符”赋值,
//setxxx(int 参数的索引(占位符)所在的位置, T ?占位符的值)。从1开始
pst.setInt(1, deptNo);
//5、再通过PreparedStatement接口实现类的对象调用executeQuery()、executeUpdate()方法执行查询、增删改等操作,
//并返回ResultSet接口类型 、int的结果
rs = pst.executeQuery();
//6、对结果进行处理。
/*next():将指针向下移动一个单位;判断是否还有下一个记录(对象)
* rs.getxxx():与数据类型相关的方法,获取相应类型的值
* rs.getxxx(int columnIndex):以字段的索引来获取对应字段的值(从1开始)
* rs.getxxx(int columnLabel):以字段的标签(指定列的值)来获取对应字段的值
*/
while (rs.next()) {
dept = new Dept();
//调用dept的各种setter方法,并将从数据库中得到相应的值作为参数传给dept的setter方法
dept.setDeptNo(rs.getInt("deptno"));
dept.setDName(rs.getString("dname"));
dept.setDName(rs.getString("loc"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7、关闭打开的资源:connection、PreparedStatement、ResultSet。
//关闭资源的顺序应采用倒叙的方式来关闭:先开的后关,后开的先关
try {
if (rs != null) {
rs.close();
}
if (pst != null) {
pst.close();
}
if (ct != null) {
ct.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//返回值,返回Dept的对象dept
return dept;
}
/**
*查询所有Dept对象的Dao层方法。
*
* @return:返回查询到的Dept对象集合
*/
public List<Dept> selectDeptAll() {
//创建一个List对象deptlist,因为查询整个数据表中的数据,所以需要一个容器来装
List<Dept> deptList = new ArrayList<Dept>();
try {
Class.forName("com.mysql.jdbc.Driver");
ct = DriverManager.getConnection("jdbc:mysql://127.0.0.1/myschool39", "root", "root");
String sql = "SELECT * FROM tb_dept";
pst = ct.prepareStatement(sql);
rs = pst.executeQuery();
Dept dept = null;
while (rs.next()) {
dept = new Dept();
dept.setDeptNo(rs.getInt("deptno"));
dept.setDName(rs.getString("dname"));
dept.setDName(rs.getString("loc"));
//将dept对象放入deptList集合中,每次循环就放入一个对象。否则就只会出现最后一个对象(记录)
deptList.add(dept);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (pst != null) {
pst.close();
}
if (ct != null) {
ct.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return deptList;
}
}
5. 编写测试类:测试com.oop.dao.impl中实现类的方法是否正确,保证调用者使用这些方法是没有问题的。
package com.oop.test;
import java.util.List;
import org.junit.Test;
import com.oop.dao.impl.DeptDaoImpl;
import com.oop.entity.Dept;
/*
* 测试类:测试DeptDaoImpl实现类中的方法是否正确
*/
public class DeptDaoImplTest {
@Test
public void testSelectDeptById() {
//实例化DeptDaoImpl类
DeptDaoImpl deptDaoImpl = new DeptDaoImpl();
//定义Dept类型的返回值对象接收selectDeptById(20)方法的返回值,并传入参数
Dept dept = deptDaoImpl.selectDeptById(20);
//输出dept
System.out.println(dept);
}
@Test
public void testSelectDeptAll() {
//实例化DeptDaoImpl类
DeptDaoImpl deptDaoImpl = new DeptDaoImpl();
//定义dept接收selectDeptAll()方法的返回值
List<Dept> dept = deptDaoImpl.selectDeptAll();
//遍历list集合
for (Dept de : dept) {
System.out.println(de);
}
}
}
运行结果:
三、 JDBC的API总结:
JDBC(Java Database Connectivity)java数据库链接,Sun公司定义了一些标准(接口、抽象类、实现类),再由数据管理系统的厂商实现对应的方法。
API(Application Programming Interface):应用程序开发接口,为完成某些特定功能而设计、开发的标准,如JDBC专门与数据库打交道的标准。
API由两个部分构成:标准的程序本身、由程序中的文档注释到处的手册称为API手册。
1、 Class.forName("com.mysql.jdbc.Driver"):获取Driver类在Class中注册的对象,通过该对象可以利用“反射机制”获取到Driver类中的所有信息。
2、 DriverManager.getConnection("jdbc:mysql://127.0.0.1/数据库名", "数据库用户名", "数据库密码"):获取与数据库的链接:需要用URL地址指定要链接哪个服务器、哪个端口、哪个数据库。
3、 Connection 接口:与数据库建立连接并可发送sql语句的接口。
Ct.prepareStatement(String sql): 向数据库发送带参数(占位符)的SQL语句,返回PreparedStatement接口实现类的对象
4、 PreparedStatement接口:预编译的SQL语句,其中提供了两类方法,一类是与数据类型相关的set方法,用于给SQL语句占位符赋值;另一类是执行操作的方法:
1) executeQuery()执行查询的方法,返回值是查询到的数据通过(ResultSet)结果集保存,再通过结果集就可以获取到查询的结果;
2) executeUpdate()执行增删改的方法,返回值是受影响的行数(int),通过它判断执行是否成功。
5、 ResultSet接口:保存执行1) executeQuery()方法得到的结果,其中两类方法:
1) ResultSet.next()方法:将指针下移一个单位;判断是否还有下一个元素
另一个getter方法与数据类型相关,指定获取哪个字段,通常将获取到值放置到对象属性的属性值
2) ResultSet.getxxx(int columnIndex):以字段的索引来获取对应字段的值(从1开始)
ResultSet.getxxx(int columnLabel):以字段的索引来获取对应字段的值