JDBC笔记-抽取JDBCUtils工具类

## 抽取JDBC工具类 : JDBCUtils



    * 目的:简化书写
    * 分析:
        1. 注册驱动也抽取
        2. 抽取一个方法获取连接对象
            * 需求:不想传递参数(麻烦),还得保证工具类的通用性。
            * 解决:配置文件
                jdbc.properties
                    driver=
                    url=
                    user=
                    password=
                **切记:值后面不要有多余空格!!!**

                3. 抽取一个方法释放资源

    * 代码实现:

emp表 sql语句

-- ----------------------------
-- Table structure for emp
-- ----------------------------
DROP TABLE IF EXISTS `emp`;
CREATE TABLE `emp`  (
  `id` int(11) NOT NULL,
  `ename` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `job_id` int(11) NULL DEFAULT NULL,
  `mgr` int(11) NULL DEFAULT NULL,
  `joindate` date NULL DEFAULT NULL,
  `salary` decimal(7, 2) NULL DEFAULT NULL,
  `bonus` decimal(7, 2) NULL DEFAULT NULL,
  `dept_id` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `emp_jobid_ref_job_id_fk`(`job_id`) USING BTREE,
  INDEX `emp_deptid_ref_dept_id_fk`(`dept_id`) USING BTREE,
  CONSTRAINT `emp_deptid_ref_dept_id_fk` FOREIGN KEY (`dept_id`) REFERENCES `dept` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `emp_jobid_ref_job_id_fk` FOREIGN KEY (`job_id`) REFERENCES `job` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of emp
-- ----------------------------
INSERT INTO `emp` VALUES (1001, '孙悟空', 4, 1004, '2000-12-17', 8000.00, NULL, 20);
INSERT INTO `emp` VALUES (1002, '卢俊义', 3, 1006, '2001-02-20', 16000.00, 3000.00, 30);
INSERT INTO `emp` VALUES (1003, '林冲', 3, 1006, '2001-02-22', 12500.00, 5000.00, 30);
INSERT INTO `emp` VALUES (1004, '唐僧', 2, 1009, '2001-04-02', 29750.00, NULL, 20);
INSERT INTO `emp` VALUES (1005, '李逵', 4, 1006, '2001-09-28', 12500.00, 14000.00, 30);
INSERT INTO `emp` VALUES (1006, '宋江', 2, 1009, '2001-05-01', 28500.00, NULL, 30);
INSERT INTO `emp` VALUES (1007, '刘备', 2, 1009, '2001-09-01', 24500.00, NULL, 10);
INSERT INTO `emp` VALUES (1008, '猪八戒', 4, 1004, '2007-04-19', 30000.00, NULL, 20);
INSERT INTO `emp` VALUES (1009, '罗贯中', 1, NULL, '2001-11-17', 50000.00, NULL, 10);
INSERT INTO `emp` VALUES (1010, '吴用', 3, 1006, '2001-09-08', 15000.00, 0.00, 30);
INSERT INTO `emp` VALUES (1011, '沙僧', 4, 1004, '2007-05-23', 11000.00, NULL, 20);
INSERT INTO `emp` VALUES (1012, '李逵', 4, 1006, '2001-12-03', 9500.00, NULL, 30);
INSERT INTO `emp` VALUES (1013, '小白龙', 4, 1004, '2001-12-03', 30000.00, NULL, 20);
INSERT INTO `emp` VALUES (1014, '关羽', 4, 1007, '2002-01-23', 13000.00, NULL, 10);

Emp.java 实体类

package cn.domain;

import java.util.Date;

/*
 * 封装Emp表的实体类
 */
public class Emp {
	private int id;
	private String ename;
	private int job_id;
	private int mgr;
	private Date joindate;
	private double salary;
	private double bonus;
	private int dept_id;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the ename
	 */
	public String getEname() {
		return ename;
	}

	/**
	 * @param ename the ename to set
	 */
	public void setEname(String ename) {
		this.ename = ename;
	}

	/**
	 * @return the job_id
	 */
	public int getJob_id() {
		return job_id;
	}

	/**
	 * @param job_id the job_id to set
	 */
	public void setJob_id(int job_id) {
		this.job_id = job_id;
	}

	/**
	 * @return the mgr
	 */
	public int getMgr() {
		return mgr;
	}

	/**
	 * @param mgr the mgr to set
	 */
	public void setMgr(int mgr) {
		this.mgr = mgr;
	}

	/**
	 * @return the joindate
	 */
	public Date getJoindate() {
		return joindate;
	}

	/**
	 * @param joindate the joindate to set
	 */
	public void setJoindate(Date joindate) {
		this.joindate = joindate;
	}

	/**
	 * @return the salary
	 */
	public double getSalary() {
		return salary;
	}

	/**
	 * @param salary the salary to set
	 */
	public void setSalary(double salary) {
		this.salary = salary;
	}



	/**
	 * @return the dept_id
	 */
	public int getDept_id() {
		return dept_id;
	}

	/**
	 * @param dept_id the dept_id to set
	 */
	public void setDept_id(int dept_id) {
		this.dept_id = dept_id;
	}

	/**
	 * @return the bonus
	 */
	public double getBonus() {
		return bonus;
	}

	/**
	 * @param bonus the bonus to set
	 */
	public void setBonus(double bonus) {
		this.bonus = bonus;
	}

	@Override
	public String toString() {
		return "Emp [id=" + id + ", ename=" + ename + ", job_id=" + job_id + ", mgr=" + mgr + ", joindate=" + joindate
				+ ", salary=" + salary + ", bonus=" + bonus + ", dept_id=" + dept_id + "]";
	}


}

JDBCUtils.java

package cn.utils;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;



/**
 * JDBC工具类
 * @author 
 */
public class JDBCUtils {
	private static String url = "";
	private static String user = "";
	private static String password = "";
	private static String driver = "";
	
	
	
	/**
	 * 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
	 */
	static {
		//读取资源文件,获取值
		
		try {
			//1.创建Properties集合类
			Properties pro = new Properties();
			
		
			
			//获取src路径下的文件的方式-->ClassLoader 类加载器
			ClassLoader classloader = JDBCUtils.class.getClassLoader();
			URL res = classloader.getResource("jdbc.properties");
			String path = res.getPath();
			System.out.println(path);
			
			//2.加载文件
			//pro.load(new FileReader("F:\\workspace2\\20200116\\src\\jdbc.properties"));
			pro.load(new FileReader(path));
			
			//3.获取数据,赋值
			url = pro.getProperty("url");
			user = pro.getProperty("user");
			password = pro.getProperty("password");
			driver = pro.getProperty("driver");
			//4.注册驱动
			Class.forName(driver);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取连接
	 * @return 连接对象
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url,user, password);
	}

	
	
	/**
	 * 释放资源
	 * @param stmt
	 * @param conn
	 */
	public static void close(Statement stmt,Connection conn) {
		if(stmt!=null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void close(ResultSet rs,Statement stmt,Connection conn) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(stmt!=null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
package cn.jdbc;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import cn.domain.Emp;
import cn.utils.JDBCUtils;

/*
 * * 定义一个方法,查询emp表的数据将其封装为对象,然后装载集合,返回。
 */
public class Jdbcdemo8 {


	
	/**
	 * 演示JDBC工具类
	 * 
	 * @return
	 */
	public List<Emp> findAll2() {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		List<Emp> list = null;
		
		try {
			/*
			 * // 1.注册驱动 Class.forName("com.mysql.jdbc.Driver"); // 2.获取连接 conn =
			 * DriverManager.getConnection("jdbc:mysql:///db2", "root", "123456");
			 */
			conn = JDBCUtils.getConnection(); 
			
			
			// 3.定义sql
			String sql = "select * from emp ";
			// 4.获取执行sql对象
			stmt = conn.createStatement();
			// 5.执行sql
			rs = stmt.executeQuery(sql);
			// 6.遍历结果集,封装对象,装载集合
			Emp emp = null;
			list = new ArrayList<Emp>();
			while (rs.next()) {
				// 获取数据
				int id = rs.getInt("id");
				String ename = rs.getString("ename");
				int job_id = rs.getInt("job_id");
				int mgr = rs.getInt("mgr");
				Date joindate = rs.getDate("joindate");
				double salary = rs.getDouble("salary");
				double bonus = rs.getDouble("bonus");
				int dept_id = rs.getInt("dept_id");
				// 创建emp对象,并赋值
				emp = new Emp();
				emp.setId(id);
				emp.setEname(ename);
				emp.setJob_id(job_id);
				emp.setMgr(mgr);
				emp.setJoindate(joindate);
				emp.setSalary(salary);
				emp.setBonus(bonus);
				emp.setDept_id(dept_id);
				
				//装载集合
				list.add(emp);
			}
		}  catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
//			if(rs!=null) {
//				try {
//					rs.close();
//				} catch (SQLException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//			
//			if(stmt!=null) {
//				try {
//					stmt.close();
//				} catch (SQLException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//			
//			if(conn!=null) {
//				try {
//					conn.close();
//				} catch (SQLException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
			JDBCUtils.close(rs, stmt, conn);
		}

		return list;
	}
	public static void main(String[] args) {
		 List<Emp> list = new Jdbcdemo8().findAll2();
		 System.out.println(list);
		 
	}
}

* 练习
        * 需求:
            1. 通过键盘录入用户名和密码
            2. 判断用户是否登录成功
                * select * from user where username = "" and password = "";
                * 如果这个sql有查询结果,则成功,反之,则失败

        * 步骤:
            1. 创建数据库表 user
                CREATE TABLE USER(
                    id INT PRIMARY KEY AUTO_INCREMENT,
                    username VARCHAR(32),
                    PASSWORD VARCHAR(32)
                
                );

                INSERT INTO USER VALUES(NULL,'zhangsan','123');
                INSERT INTO USER VALUES(NULL,'lisi','234');

            2. 代码实现:

package cn.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

import cn.utils.JDBCUtils;

/**
 * * 练习:
		* 需求:
			1. 通过键盘录入用户名和密码
			2. 判断用户是否登录成功
 *
 */
public class Jdbcdemo9 {
	/**
	  *   登录方法
	 * @return
	 */
	public boolean login(String username,String password) {
		if(username == null || password == null) {
			return false;
		}
		
		//连接数据库判断是否登录成功
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			//1.获取连接
			conn = JDBCUtils.getConnection();
			//2.定义sql
			String sql = "select * from user where username = '"+username+"' and password = '"+password+"' ";
			//3.获取执行sql的对象
			stmt = conn.createStatement();
			//4.执行查询
			rs = stmt.executeQuery(sql);
			//5.判断
			return rs.next();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCUtils.close(rs, stmt, conn);
		}
		return false;
	}
	public static void main(String[] args) {
		//1.键盘录入,接受用户名和密码
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入用户名");
		String username = sc.nextLine();
		System.out.println("请输入密码");
		String password = sc.nextLine();
		//2.调用方法
		boolean flag = new Jdbcdemo9().login(username, password);
		//3.判断结果,输出不同	语句
		if(flag) {
			//登录成功
			System.out.println("登录成功");
		}else {
			//登录失败
			System.out.println("用户名或密码错误");
		}
	}
}




发布了26 篇原创文章 · 获赞 6 · 访问量 4492

猜你喜欢

转载自blog.csdn.net/IT_world_/article/details/104109651