练习数据库
需求
- 修改1号数据的 salary 为10000
- 添加一条记录
- 删除刚才添加的记录
- 查询 id 为 1 记录,将其封装为Map集合
- 查询所有记录, 将其封装为List
- 查询所有记录, 将其封装为Emp对象的List集合
- 查询总的记录数
具体操作
因为要对一个emp数据表进行操作, 所以要封装一个emp对象
这里的数据类型不用基本数据类型,改成引用数据类型
package domain;
import java.util.Date;
/*
* 对应封装EMP表数据的JavaBean
*/
public class Emp {
private Integer id;
private String ename;
private String gender;
private Date joindate;
private Double salary;
private Integer dept_id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getJoindate() {
return joindate;
}
public void setJoindate(Date joindate) {
this.joindate = joindate;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Integer getDept_id() {
return dept_id;
}
public void setDept_id(Integer dept_id) {
this.dept_id = dept_id;
}
@Override
public String toString() {
return "Emp{" +
"id=" + id +
", ename='" + ename + '\'' +
", gender='" + gender + '\'' +
", joindate=" + joindate +
", salary=" + salary +
", dept_id=" + dept_id +
'}';
}
}
加载这些jar包
准备好druid.properties配置文件
username=root
password=qq124519
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db2?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8&useUnicode=yes
initialSize=10
maxActive=50
maxWait=3000
创建一个JDBCUtils类,加载配置文件
package JdbcTemplate;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
//定义成员变量DataSource
private static DataSource ds;
//对静态变量进行初始化值
static {
//1.加载配置文件
Properties pro = new Properties();
//通过load方法加载
try {
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection ();
}
/**
* 释放资源
*/
public static void close(Statement stmt, Connection conn) {
if (stmt != null) {
try {//把异常处理而不是抛出去是为了使关闭的方法更加简单
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//再来一个重载
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {//把异常处理而不是抛出去是为了使关闭的方法更加简单
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 获取连接池的方法
*/
public static javax.sql.DataSource getDataSource() {
return ds;
}
}
建立JdbcTemplateDemo测试类,使用**Junit单元测试**的方法
package JdbcTemplate;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcTemplateDemo {
//Junit单元测试, 可以让方法独立执行
//获取JDBCTemplate对象
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 修改1号数据的 salary 为10000
*/
@Test
public void test1() {
//定义SQL
String sql = "update emp set salary = 10000 where id = 1";
//执行SQL
int count = template.update(sql);
System.out.println(count);
}
/**
* 添加一条记录
*/
@Test
public void test2() {
//定义SQL
String sql = "insert into emp(id,name,dept_id) values(?,?,?)";//防止SQL注入
int count = template.update(sql, 7, "郭靖", 1);
System.out.println(count);
}
/**
* 删除刚才添加的记录
*/
@Test
public void test3() {
String sql = "delete from emp where id = ?";//防止SQL注入
int count = template.update(sql, 7);
System.out.println(count);
}
/**
* 查询id为 1 的记录, 将其封装为Map集合
* 注意: 这个方法查询的结果集长度只能是1
*/
@Test
public void test4(){
String sql="select * from emp where id = ?";
Map<String, Object> map = template.queryForMap(sql, 1);
System.out.println(map);
//{id=1, name=孙悟空, gender=男, salary=10000.0, join_date=2013-02-04, dept_id=1}
}
/**
* 查询两条以上的记录
* 查询所有记录, 将其封装为List
*/
@Test
public void test5() {
String sql = "select *from emp";
List<Map<String, Object>> list = template.queryForList(sql);
//遍历
for (Map<String, Object> stringObjectMap:list){
System.out.println(stringObjectMap);
}
//查询结果
/*{id=1, name=孙悟空, gender=男, salary=10000.0, join_date=2013-02-04, dept_id=1}
{id=2, name=猪八戒, gender=男, salary=3600.0, join_date=2010-12-24, dept_id=2}
{id=3, name=唐僧, gender=男, salary=9000.0, join_date=2008-08-08, dept_id=2}
{id=4, name=白骨精, gender=女, salary=5000.0, join_date=2015-10-17, dept_id=3}
{id=5, name=蜘蛛精, gender=女, salary=4500.0, join_date=2011-03-14, dept_id=1}
{id=6, name=小白龙, gender=男, salary=3000.0, join_date=null, dept_id=null}*/
}
}
查询所有记录, 将其封装为Emp对象的List集合
/**
* 查询所有记录, 将其封装为Emp对象的List集合
*/
@Test
public void test6(){
String sql="select * from emp";
List<Emp> list = template.query(sql, new RowMapper<Emp>() {//要封装什么对象就加什么泛型
@Override//每调用一次就会封装城一个emp对象返回给你
public Emp mapRow(ResultSet rs, int i) throws SQLException {
Emp emp =new Emp();
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
double salary = rs.getDouble("salary");
Date join_date = rs.getDate("join_date");
int dept_id = rs.getInt("dept_id");
emp.setId(id);
emp.setEname(name);
emp.setGender(gender);
emp.setSalary(salary);
emp.setJoindate(join_date);
emp.setDept_id(dept_id);
//返回emp对象
return emp;
}
});
//遍历Emp对象集合
for (Emp emp:list){
System.out.println(emp);
}
}
结果
由于上一个方法代码量过多,我们可以借助已有的端口来实现查询的功能,代码如下
@Test
public void test6_2(){
String sql="select * from emp";
List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
for (Emp emp:list){
System.out.println(emp);
}
}
这时如果是基本数据类型的话可能会报错 , 所以 Emp 对象的成员变量的数据类型要改成应用数据类型