1.Java连接数据库步骤
1.注册驱动
Class<?> driverManager=Class.forName("com.mysql.cj.jdbc.Driver");2.获取连接
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/studymysql","root","123456");3.执行sql
String sql="select * from emp"; PreparedStatement ps=con.prepareStatement(sql);4.返回sql执行结果
ResultSet rs=ps.executeQuery(); while (rs.next()){ System.out.println("员工Id"+rs.getInt("empno")+"\t员工姓名"+rs.getString("ename")); }
2.JDBC工具类
-
1.先创建db.properties文件
# Database configuration properties driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/studymysql username=root password=123456
-
2.然后创建jdbc工具类读取properties文件,获取连接对象
package com.pyb.utils; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; public class JdbcUtils { private static final HikariDataSource dataSource; static { Properties props = new Properties(); try (InputStream input = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties")) { props.load(input); HikariConfig config = new HikariConfig(); config.setDriverClassName(props.getProperty("driver")); config.setJdbcUrl(props.getProperty("url")); config.setUsername(props.getProperty("username")); config.setPassword(props.getProperty("password")); // 可选配置项,可以根据需要添加更多配置 // config.setMaximumPoolSize(10); // 设置最大连接数 dataSource = new HikariDataSource(config); } catch (IOException e) { throw new RuntimeException("Error loading database properties.", e); } } /** * 获取数据库连接对象 * @return 数据库连接对象 */ public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } /** * 关闭数据库相关资源 */ public static void close(Connection conn, PreparedStatement ps, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException ignored) {} } if (ps != null) { try { ps.close(); } catch (SQLException ignored) {} } if (conn != null) { try { conn.close(); } catch (SQLException ignored) {} } } // 你可以根据需要保留其他重载的 close 方法 // 确保在应用关闭时正确关闭数据源 public static void destroy() { if (dataSource != null) { dataSource.close(); } } }
3.写持久层业务逻辑实现增删改查
-
1.先准备好sql表
/* Navicat Premium Data Transfer Source Server : localhost_3306 Source Server Type : MySQL Source Server Version : 80037 (8.0.37) Source Host : localhost:3306 Source Schema : studymysql Target Server Type : MySQL Target Server Version : 80037 (8.0.37) File Encoding : 65001 Date: 24/12/2024 11:32:08 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for emp -- ---------------------------- DROP TABLE IF EXISTS `emp`; CREATE TABLE `emp` ( `empno` int NOT NULL AUTO_INCREMENT COMMENT '雇员编号', `ename` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '雇员姓名', `job` varchar(9) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '表示工作职位', `mgr` int NULL DEFAULT NULL COMMENT '表示一个雇员的领导编号', `hiredate` datetime NULL DEFAULT NULL COMMENT '表示雇佣日期', `sal` double NULL DEFAULT NULL COMMENT '表示月薪,工资', `comm` double NULL DEFAULT NULL COMMENT '表示奖金或佣金', `deptno` int NULL DEFAULT NULL, PRIMARY KEY (`empno`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of emp -- ---------------------------- SET FOREIGN_KEY_CHECKS = 1;
-
2.编写pojo映射数据库属性
package com.pyb.pojo; /** * @version 1.0 * @Author 彭彦彬 * @Date 2024/12/24 15:07 * @注释 */ public class Emp { private int empNo; private String eName; private String job; private int mgr; private String hireDate; private double sal; private double comm; private int deptNo; public Emp(int empNo, String eName, String job, int mgr, String hireDate, double sal, double comm, int deptNo) { 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 Emp(String eName, String job, int mgr, String hireDate, double sal, int deptNo, double comm) { this.eName = eName; this.job = job; this.mgr = mgr; this.hireDate = hireDate; this.sal = sal; this.deptNo = deptNo; this.comm = comm; } @Override public String toString() { return "Emp{" + "empNo=" + empNo + ", eName='" + eName + '\'' + ", job='" + job + '\'' + ", mgr=" + mgr + ", hireDate='" + hireDate + '\'' + ", sal=" + sal + ", comm=" + comm + ", deptNo=" + deptNo + '}'; } public Emp() { } public int getEmpNo() { return empNo; } public void setEmpNo(int 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 int getMgr() { return mgr; } public void setMgr(int mgr) { this.mgr = mgr; } public String getHireDate() { return hireDate; } public void setHireDate(String 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 int getDeptNo() { return deptNo; } public void setDeptNo(int deptNo) { this.deptNo = deptNo; } }
-
3.dao层接口
package com.pyb.dao; import com.pyb.pojo.Emp; import java.sql.SQLException; import java.util.List; /** * @version 1.0 * @Author 彭彦彬 * @Date 2024/12/25 10:17 * @注释 */ public interface EmpDao { /** * 获取所有用户数据 * @return */ List<Emp> list() throws SQLException; /** * 查询员工信息通过姓名 * @param name * @return */ Emp selectEmpByName(String name) throws SQLException; /** * 添加員工信息 * @param emp */ int addEmp(Emp emp); int deleteEmp(Emp emp); }
-
4.dao层接口实现类
package com.pyb.dao.daoImpl; import com.pyb.dao.EmpDao; import com.pyb.pojo.Emp; import com.pyb.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * @version 1.0 * @Author 彭彦彬 * @Date 2024/12/25 10:19 */ public class EmpDaoImpl implements EmpDao { @Override public List<Emp> list() throws SQLException { String sql = "SELECT * FROM emp"; List<Emp> list = new ArrayList<>(); // 使用 try-with-resources 确保资源自动关闭 try (Connection con = JdbcUtils.getConnection(); PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery()) { while (rs.next()) { int empno = rs.getInt("empno"); String ename = rs.getString("ename"); String job = rs.getString("job"); int mgr = rs.getInt("mgr"); String hiredate = rs.getString("hiredate"); // 如果 hiredate 是日期类型 double sal = rs.getDouble("sal"); double comm = rs.getDouble("comm"); int deptno = rs.getInt("deptno"); list.add(new Emp(empno, ename, job, mgr, hiredate, sal, comm, deptno)); } } catch (SQLException e) { // 记录详细的错误信息,以便于调试 e.printStackTrace(); // 在实际应用中应使用日志框架如 SLF4J 等记录错误信息 throw e; // 或者抛出自定义异常 } return list; } @Override public Emp selectEmpByName(String name) throws SQLException { String sql = "SELECT * FROM emp WHERE ename = ?"; // 使用 try-with-resources 确保资源自动关闭 try (Connection con = JdbcUtils.getConnection(); PreparedStatement ps = con.prepareStatement(sql)) { ps.setString(1, name); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { int empno = rs.getInt("empno"); String ename = rs.getString("ename"); String job = rs.getString("job"); int mgr = rs.getInt("mgr"); String hiredate = rs.getString("hiredate"); // 如果 hiredate 是日期类型 double sal = rs.getDouble("sal"); double comm = rs.getDouble("comm"); int deptno = rs.getInt("deptno"); return new Emp(empno, ename, job, mgr, hiredate, sal, comm, deptno); } } // 如果没有找到员工,则返回 null return null; } catch (SQLException e) { // 记录详细的错误信息,以便于调试 e.printStackTrace(); // 在实际应用中应使用日志框架如 SLF4J 等记录错误信息 throw e; // 或者抛出自定义异常 } } @Override public int addEmp(Emp emp) { String sql="insert into emp(ename,job,mgr,hiredate,sal,comm,deptno)values(?,?,?,?,?,?,?)"; int effect=0; // 使用 try-with-resources 确保资源自动关闭 try (Connection con = JdbcUtils.getConnection(); PreparedStatement ps = con.prepareStatement(sql)) { ps.setString(1,emp.geteName()); ps.setString(2,emp.getJob()); ps.setInt(3,emp.getMgr()); ps.setString(4,emp.getHireDate()); ps.setDouble(5, emp.getSal()); ps.setDouble(6,emp.getComm()); ps.setInt(7,emp.getDeptNo()); effect=ps.executeUpdate(); } catch (SQLException e) { // 记录详细的错误信息,以便于调试 e.printStackTrace(); // 在实际应用中应使用日志框架如 SLF4J 等记录错误信息 } return effect; } @Override public int deleteEmp(Emp emp) { String sql = "DELETE FROM emp WHERE empno = ?"; int affectedRows = 0; // 使用 try-with-resources 确保资源自动关闭 try (Connection con = JdbcUtils.getConnection(); PreparedStatement ps = con.prepareStatement(sql)) { ps.setInt(1, emp.getEmpNo()); affectedRows = ps.executeUpdate(); if (affectedRows == 0) { System.out.println("Warning: No rows were deleted for empno=" + emp.getEmpNo()); // 可选择抛出自定义异常或返回特定值以表示未找到要删除的记录 } else { System.out.println("Employee with empno=" + emp.getEmpNo() + " deleted successfully."); } } catch (SQLException e) { // 记录详细的错误信息,以便于调试 e.printStackTrace(); // 在实际应用中应使用日志框架如 SLF4J 等记录错误信息 // 抛出自定义异常或进行其他适当的错误处理 throw new RuntimeException("Database error occurred while deleting employee.", e); } return affectedRows; } }
-
5.最后进行测试即可