(JAVA)05——JDBC

这篇博客详细介绍了如何使用Java JDBC与MySQL数据库进行交互,包括建立连接、操作数据库的类和接口、查询、删除、更新和插入数据等功能。通过Emp类和EmpDao接口实现数据管理,EmpDaoLmpl作为接口实现类,EmpService及EmpServiceImpl分别表示业务层接口和实现,同时提供了测试类进行功能验证。

JDBC技术

JDBC——Java DataBase Connection——Java数据库连接

使用MySQL官方提供的驱动:

mysql-connector-java-8.0.21.jar

操作数据库的类或接口

①、在项目中加载驱动:
添加jar包

在这里插入图片描述

②、封装一个工具类:BaseDao
③、创建一个POJO类
④、创建一个接口
⑤、创建一个接口实现类

查询功能:

在这里插入图片描述
————————————————————————————————————————

以下为代码部分

在这里插入图片描述

Emp.java----->定义了一个员工类Emp

package bean;

import java.util.Date;

public class Emp
{
	private Integer empno;   // 员工编号
	private String  ename;   // 员工姓名
	private String  job;     // 工作职位
	private Integer mgr;     // 领导编号
	private Date    hiredate;// 入职日期
	private Double  sal;     // 员工工资
	private Double  comm;    // 员工奖金
	private Integer deptno;  // 部门编号

	public Emp()
	{
		super();
	}

	public Emp(Integer empno, String ename, String job, Integer mgr, Date hiredate, Double sal, Double comm, Integer deptno)
	{
		super();
		this.empno    = empno;
		this.ename    = ename;
		this.job      = job;
		this.mgr      = mgr;
		this.hiredate = hiredate;
		this.sal      = sal;
		this.comm     = comm;
		this.deptno   = deptno;
	}

	public Integer getEmpno()
	{
		return empno;
	}

	public void setEmpno(Integer empno)
	{
		this.empno = empno;
	}

	public String getEname()
	{
		return ename;
	}

	public void setEname(String ename)
	{
		this.ename = ename;
	}

	public String getJob()
	{
		return job;
	}

	public void setJob(String job)
	{
		this.job = job;
	}

	public Integer getMgr()
	{
		return mgr;
	}

	public void setMgr(Integer mgr)
	{
		this.mgr = mgr;
	}

	public Date getHiredate()
	{
		return hiredate;
	}

	public void setHiredate(Date hiredate)
	{
		this.hiredate = hiredate;
	}

	public Double getSal()
	{
		return sal;
	}

	public void setSal(Double sal)
	{
		this.sal = sal;
	}

	public Double getComm()
	{
		return comm;
	}

	public void setComm(Double comm)
	{
		this.comm = comm;
	}

	public Integer getDeptno()
	{
		return deptno;
	}

	public void setDeptno(Integer deptno)
	{
		this.deptno = deptno;
	}

	@Override
	public String toString()
	{
		return "Emp [empno=" + empno + ", ename=" + ename + ", job=" + job + ", mgr=" + mgr + ", hiredate=" + hiredate + ", sal=" + sal + ", comm=" + comm + ", deptno=" + deptno + "]";
	}
}

————————————————————————————————————————

EmpDao.java------>定义了员工管理系统的功能模块接口

package dao;

import java.sql.SQLException;
import java.util.List;
import bean.Emp;

/*
 * 定义员工管理系统的功能模块
 */
public interface EmpDao
{
	// 查询信息
	public abstract List<Emp> select(Emp emp) throws SQLException;

	// 删除指定信息
	public abstract Integer delete(Emp emp) throws SQLException;

	// 更新指定信息
	public abstract Integer update(Emp emp) throws SQLException;

	// 添加信息
	public abstract Integer insert(Emp emp) throws SQLException;
}

————————————————————————————————————————

EmpDaoLmpl.java------>功能接口的实现类

package impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import bean.Emp;
import dao.EmpDao;
import util.BaseDao;

public class EmpDaoImpl implements EmpDao
{
	private Connection        connection        = null;
	private PreparedStatement preparedStatement = null;
	private ResultSet         resultSet         = null;

	// 查询信息
	@Override
	public List<Emp> select(Emp emp) throws SQLException
	{
		List<Emp>    list = new ArrayList<>();
//		String            sql               = "select * from emp where deptno=? and sal>?";
		StringBuffer sql  = new StringBuffer("select * from emp where 1=1");
		// 动态SQL语句的拼接
		if (emp.getDeptno() != null)
		{
			sql.append(" and deptno=" + emp.getDeptno());
		}
		if (emp.getSal() != null)
		{
			sql.append(" and sal>" + emp.getSal());
		}
		try
		{
			// 获取数据库连接
			connection        = BaseDao.getConnection();
			// 对SQL进行预处理:?占位符
			preparedStatement = connection.prepareStatement(sql.toString());
			// 给占位符填充值
//			preparedStatement.setInt(1, emp.getDeptno());
//			preparedStatement.setDouble(2, emp.getSal());
			// 获取数据库中的数据存储在结果集:resultSet
			resultSet         = preparedStatement.executeQuery();
			while (resultSet.next())
			{
				Emp emp2 = new Emp();
				emp2.setEmpno(resultSet.getInt("empno"));
				emp2.setEname(resultSet.getString("ename"));
				emp2.setJob(resultSet.getString("job"));
				emp2.setMgr(resultSet.getInt("mgr"));
				emp2.setHiredate(resultSet.getDate("hiredate"));
				emp2.setSal(resultSet.getDouble("sal"));
				emp2.setComm(resultSet.getDouble("comm"));
				emp2.setDeptno(resultSet.getInt("deptno"));
				// 将相应的数据以对象的形式添加到list集合中
				list.add(emp2);
			}
		}catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}finally
		{
			BaseDao.closeDataBase(resultSet, preparedStatement, connection);
		}
		return list;
	}

	// 删除指定信息:删除指定部门编号的员工信息
	@Override
	public Integer delete(Emp emp) throws SQLException
	{
		String  sql   = "delete from emp where deptno=?";
		Integer count = 0;
		try
		{
			// 获取数据库的连接
			connection        = BaseDao.getConnection();
			// SQL语句预处理
			preparedStatement = connection.prepareStatement(sql);
			// 填充占位符
			preparedStatement.setInt(1, emp.getDeptno());
			// executeUpdate:删除、更新和添加操作
			count = preparedStatement.executeUpdate();
			// 输出SQL语句
			System.out.println("preparedStatement = " + preparedStatement);
		}catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}finally
		{
			BaseDao.closeDataBase(resultSet, preparedStatement, connection);
		}

		return count;
	}

	// 更新指定部门的员工工资
	@Override
	public Integer update(Emp emp) throws SQLException
	{
		String  sql   = "update emp set sal =sal + ? where deptno=?";
		Integer count = 0;
		try
		{
			connection        = BaseDao.getConnection();
			preparedStatement = connection.prepareStatement(sql);
			// 填充占位符
			preparedStatement.setDouble(1, emp.getSal());
			preparedStatement.setInt(2, emp.getDeptno());
			// 执行更新操作
			count = preparedStatement.executeUpdate();
			System.out.println("preparedStatement = " + preparedStatement);
		}catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}finally
		{
			BaseDao.closeDataBase(resultSet, preparedStatement, connection);
		}
		return count;
	}

	@Override
	public Integer insert(Emp emp) throws SQLException
	{
		String  sql   = "insert into emp(ename,job,mgr,hiredate,sal,comm,deptno) values(?,?,?,now(),?,?,?)";
		Integer count = 0;
		try
		{
			connection        = BaseDao.getConnection();
			preparedStatement = connection.prepareStatement(sql);
			// 填充占位符
			preparedStatement.setString(1, emp.getEname());
			preparedStatement.setString(2, emp.getJob());
			preparedStatement.setInt(3, emp.getMgr());
			preparedStatement.setDouble(4, emp.getSal());
			preparedStatement.setDouble(5, emp.getComm());
			preparedStatement.setInt(6, emp.getDeptno());
			// 执行添加操作
			count = preparedStatement.executeUpdate();
			System.out.println("preparedStatement = " + preparedStatement);
		}catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}finally
		{
			BaseDao.closeDataBase(resultSet, preparedStatement, connection);
		}
		return count;
	}
}

————————————————————————————————————————

EmpSercie.java------>业务层功能模块接口

package services;

import java.sql.SQLException;
import java.util.Map;
import bean.Emp;

/*
 * 业务层
 */
public interface EmpSercie
{
	// 获取员工信息
	public abstract Map<String, Object> getEmpAllInfo(Emp emp) throws SQLException;

	// 删除指定信息
	public abstract Map<String, Object> removeByDeptno(Emp emp) throws SQLException;
}

————————————————————————————————————————

EmpserviceImpl.java------>业务层接口实现

package services.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import bean.Emp;
import dao.EmpDao;
import impl.EmpDaoImpl;
import services.EmpSercie;

public class EmpserviceImpl implements EmpSercie
{

	@Override
	public Map<String, Object> getEmpAllInfo(Emp emp) throws SQLException
	{
		EmpDao    empDao = new EmpDaoImpl();
		List<Emp> list   = new ArrayList<>();
		// 调用数据访问层
		list = empDao.select(emp);
		Map<String, Object> map = new HashMap<>();
		if (list.size() > 0)
		{
			map.put("code", "0");
			map.put("message", "查询数据成功!");
			map.put("flag", true);
			map.put("list", list);
		}else
		{
			map.put("code", "1");
			map.put("message", "查询数据失败!");
			map.put("flag", false);
			map.put("count", list.size());
		}
		return map;
	}

	@Override
	public Map<String, Object> removeByDeptno(Emp emp) throws SQLException
	{
		EmpDao              empDao = new EmpDaoImpl();
		Integer             count  = 0;
		Map<String, Object> map    = new HashMap<>();
		count = empDao.delete(emp);
		if (count >= 1)
		{
			map.put("code", "0");
			map.put("message", "数据删除成功!");
			map.put("flag", true);
			map.put("count", count);
		}else
		{
			map.put("code", "0");
			map.put("message", "数据删除失败!");
			map.put("flag", false);
			map.put("count", count);
		}
		return map;
	}

}

————————————————————————————————————————

test-package------->测试类

选择数据


package test;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import bean.Emp;
import dao.EmpDao;
import impl.EmpDaoImpl;

public class Test2
{

	public static void main(String[] args)
	{
		Emp       emp    = new Emp(7788, "SCOTT", "ANALYST", 7566, new Date(), 2000.00, 1000.00, 20);
		List<Emp> list   = new ArrayList<>();
		EmpDao    empDao = new EmpDaoImpl();
		try
		{
			list = empDao.select(emp);
			for (Emp emp2 : list)
			{
				System.out.println(emp2.toString());
			}
		}catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

}

删除数据

package test;

import java.sql.SQLException;
import java.util.Date;
import bean.Emp;
import dao.EmpDao;
import impl.EmpDaoImpl;

public class Test3
{

	public static void main(String[] args)
	{
		Emp     emp    = new Emp(7788, "SCOTT", "ANALYST", 7566, new Date(), 2000.00, 1000.00, 20);
		Integer count  = 0;
		EmpDao  empDao = new EmpDaoImpl();
		try
		{
			count = empDao.delete(emp);
			System.out.println("count = " + count);
			if (count >= 1)
			{
				System.out.println("数据删除成功!");
			}else
			{
				System.out.println("数据删除失败!");
			}
		}catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

}

还有更新和插入功能


	empDao.update();
	empDao.insert();

————————————————————————————————————————

BaseDao.java------->定义数据库的连接和关闭相关资源

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
 * 定义数据库的连接和关闭相关资源
 */
public class BaseDao
{
	// 定义数据库连接参数
	private static String user = "root";
	private static String password = "";
	private static String driver = "com.mysql.cj.jdbc.Driver";
	private static String url = "jdbc:mysql://127.0.0.1:3306/empdb?allowPublicKeyRetrieval=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false";

	// 获取数据库的连接
	public static Connection getConnection() throws ClassNotFoundException, SQLException
	{
		Connection connection = null;
		// 加载驱动
		Class.forName(driver);
		// 获取连接
		connection = DriverManager.getConnection(url, user, password);
		return connection;
	}

	// 关闭数据库相关资源
	public static void closeDataBase(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection)
			throws SQLException
	{
		if (resultSet != null)
		{
			resultSet.close();
		}
		if (preparedStatement != null)
		{
			preparedStatement.close();
		}
		if (connection != null)
		{
			connection.close();
		}
	}
}

————————————————————————————————————————

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值