JDBCUtils工具類的編寫和練習

上片文中因爲JDBC數據庫中大量重複代碼,導致代碼複用率低,健壯性不高,需要整合一個工具類。本片筆記來學習記錄編寫JDBC工具類

JDBCUtils.class的編寫

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

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();
			//加載文件
			//pro.load(new FileReader("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");
			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();
		}
	}
	
	
	/**
	 * 獲取鏈接的方法
	 * 不想傳遞參數(麻煩),還得保證工具類的通用型
	 * 		解決:配置文件
	 * 		jdbc.properties
	 * 			url=
	 * 			user=
	 * 			password=
	 * @return 連接對象
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException{

		return DriverManager.getConnection(url,user,password);
	}
	
	/**
	 * 釋放資源的方法
	 */
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();
			}
		}
	}
}

jdbc.properties文件,將有關數據庫的,url、用戶名、密碼,都寫在這個文件中,以後修改數據庫的相關信息,可直接修改此文件

url=jdbc:mysql:///db4
user=root
password=123456
driver=com.mysql.jdbc.Driver

然後做一個測試

JavaBean: Emp.class

package com.zqyzc.domain;

import java.util.Date;

/**
 * 封裝Emp表數據的JavaBean
 * @author 92086
 *
 */
public class Emp {
	private int id;
	private String name;
	private boolean gender;
	private Date birthday;
	
	public Emp() {
		super();
	}
	public Emp(int id, String name, boolean gender, Date birthday) {
		super();
		this.id = id;
		this.name = name;
		this.gender = gender;
		this.birthday = birthday;
	}

	//set和get方法節省篇幅,略

	@Override
	public String toString() {
		return "Emp [id=" + id + ", name=" + name + ", gender=" + gender + ", birthday=" + birthday + "]";
	}
}

測試類:

package com.zqyzc.com;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import com.zqyzc.domain.Emp;
import com.zqyzc.util.JDBCUtils;

/**
 * 定義一個方法,查詢emp表的數據並封裝爲對象,然後裝載集合,返回。
 * @author 92086
 *
 */
public class mysqlTestEmp2 {
	
	public static void main(String[] args){
		List<Emp> list = new mysqlTestEmp2().findAll2();
		System.out.println(list);
		System.out.println(list.size());
	}
	
	/**
	 * 演示JDBCUtils工具類
	 */
	public List<Emp> findAll2(){
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		List<Emp> list = null;
		try {	
			//使用工具類註冊驅動鏈接數據庫
			conn = JDBCUtils.getConnection();
			//定義sql
			String sql = "select * from student";
			//獲取執行sql的對象
			stmt = conn.createStatement();
			
			rs = stmt.executeQuery(sql);
			//6、遍歷結果集、封裝對象裝載集合
			Emp emp = null;
			list = new ArrayList<Emp>();
			while(rs.next()){
				int id = rs.getInt("id");
				String name = rs.getString("name");
				boolean gender = rs.getBoolean("gender");
				Date birthday = rs.getDate("birthday");
				emp = new Emp(id,name,gender,birthday);
				list.add(emp);
			}
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			JDBCUtils.close(rs, stmt, conn);
		}
		return list;
	}

}

 

做一個小小的案例,實現登陸功能

工具類使用的是上述工具類。因簡易實現登陸功能,就使用控制檯來做

爲防止sql注入,使用了Statement的子類,PrepareStatement類

package com.zqyzc.com;

import java.sql.*;
import java.util.Scanner;

import com.zqyzc.util.JDBCUtils;

public class mysqlTsetLogin {
	/**
	 * 登陸方法
	 * @param args
	 */
	public boolean login(String username,String password){
		if(username == null || password == null){
			return false;
		}
		//鏈接數據庫來判斷登陸是否成功
		
		//1、獲取鏈接
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = JDBCUtils.getConnection();
			//2、定義sql
			String sql = "select * from user where username = ? and password = ?";
			//3、獲取執行sql的對象
			pstmt = conn.prepareStatement(sql);
			//3.2給問號賦值
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			//4、執行查詢,不需要傳遞sql
			rs = pstmt.executeQuery();
			//5、判斷
			return rs.next();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			JDBCUtils.close(rs,pstmt, 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 mysqlTsetLogin().login(username, password);
		//3、判斷結果,輸出不同語句
		if(flag){
			System.out.println("登陸成功");
		}else{
			System.out.println("用戶名或密碼錯誤!");
		}
	}

}

結果

 

數據庫內容

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章