Java(九)数据库JDBC:5.JDBC的写法三:更加标准化


一、JDBCUtil

package Utils;

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

public class JDBCUtil {

	// mysql驱动
	private static final String JDBC_DRIVER_8UP = "com.mysql.cj.jdbc.Driver";

	// 名为mandarin的数据库名url
	private static final String DB_URL_8UP = "jdbc:mysql://localhost:3306/mandarin?useSSL=false&serverTimezone=UTC&&allowPublicKeyRetrieval=true";

	// 用户名
	private static final String user = "root";

	// 密码
	private static final String password = "1234";

	private static Connection con = null;
	private static Statement stmt = null;
	private static PreparedStatement pstmt = null;
	private static ResultSet rs = null;

	// 链接数据库
	public static void init() {
		try {
			Class.forName(JDBC_DRIVER_8UP);
			con = DriverManager.getConnection(DB_URL_8UP, user, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("[DB init] ClassNotFoundException");
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("[DB init] SQLException");
		}
	}

	// 关闭用到的Connection、Statement、PreparedStatement、ResultSet
	public static void close() {
		try {
			if (con != null) {
				con.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (pstmt != null) {
				pstmt.close();
			}
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			System.out.println("[DB close] SQLException");
			e.printStackTrace();
		}
	}

	// Statement的executeUpdate()封装
	public static int insDelUpd(String sql) {
		int flag = 0;
		try {
			stmt = con.createStatement();
			flag = stmt.executeUpdate(sql);
		} catch (SQLException e) {
			System.out.println("[DB insDelUpd] SQLException");
			e.printStackTrace();
		}
		return flag;
	}

	// Statement的executeQuery()封装
	public static ResultSet select(String sql) {
		try {
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			System.out.println("[DB select] SQLException");
			e.printStackTrace();
		}
		return rs;
	}

	// PreparedStatement的executeUpdate()封装
	public static int insDelUpd(String sql, Object[] param) {
		int flag = 0;
		try {
			pstmt = con.prepareStatement(sql);
			if (param != null) {
				for (int i = 0; i < param.length; i++) {
					pstmt.setObject(i + 1, param[i]);
				}
			}
			flag = pstmt.executeUpdate();
		} catch (SQLException e) {
			System.out.println("[DB insDelUpd] SQLException");
			e.printStackTrace();
		}
		return flag;
	}

	// PreparedStatement的executeQuery()封装
	public static ResultSet select(String sql, Object[] param) {
		try {
			pstmt = con.prepareStatement(sql);
			if (param != null) {
				for (int i = 0; i < param.length; i++) {
					pstmt.setObject(i + 1, param[i]);
				}
			}
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			System.out.println("[DB select] SQLException");
			e.printStackTrace();
		}
		return rs;
	}
	
//	public static void main(String[] args) {
//		JDBCUtil.init();
//		JDBCUtil.addDel("DELETE from `mandarin`.`user`	where userId = 3;");
//		JDBCUtil.close();
//	}
}

二、User

package Model;

// 8个属性
public class User {
	// 用户名
	private int userId;
	
	// 密码
	private String password;

	// 名字
	private String userName;
	
	// 性别 0男 1女
	private int sex;
	
	// 年龄
	private int age;
	
	// 邮箱
	private String email;
	
	// 手机
	private String phone;
	
	// 用户类型 reader librarian admin
	private String type;

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public int getSex() {
		return sex;
	}

	public void setSex(int sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
}

三、LibrarianDAO

package DAO;

import Model.User;

public interface LibrarianDAO {
	/**
	 * registReader() 注册读者, 后端需要生成新的userid并返回
	 * (思索再三,感觉需求中用手机号作为id并不太好,这样一旦注册就无法更改手机号,所以还是用自动生成的id作为用户名吧)
	 * 
	 * 参数; { userName:xxx,//名字 sex:xxx,//性别 0男 1女 age:xxx,//年龄 password:xxx,//密码
	 * email:xxx,//邮箱 phone:xxx//手机
	 * 
	 * }//所有参数都可缺省,全部缺省情况默认密码12345678
	 * 
	 * 返回:{ status:xxx, //0: 注册失败 200: 注册成功 userid:xxx //返回新的用户id }
	 */
	public String registerReader(String userName, int sex, int age, String password, String email, String phone);

	/**
	 * 获得读者的信息
	 * 
	 * @param account 读者账号
	 * 
	 * Reader先为null,这样如果成功获取了数据返回创建好的Reader 失败了就返回null。
	 */
	public User getReader(int userId);
	
	/**
	 * 编辑读者信息
	 * 
	 * @param 传入一个Reader
	 */
	public boolean editReader(User reader);
	
	/**
	 * 删除读者
	 * 
	 * @param userId 读者账号
	 */
	public boolean deleteReader(int userId);
}

四、LibrarianDAOImpl

package DAO;

import java.sql.ResultSet;
import java.sql.SQLException;

import Model.User;
import Utils.JDBCUtil;
import Utils.StringUtil;

public class LibrarianDAOImpl implements LibrarianDAO {

	/**
	 * registReader() 注册读者, 后端需要生成新的userid并返回
	 * (思索再三,感觉需求中用手机号作为id并不太好,这样一旦注册就无法更改手机号,所以还是用自动生成的id作为用户名吧)
	 * 
	 * 参数; { userName:xxx,//名字 sex:xxx,//性别 0男 1女 age:xxx,//年龄 password:xxx,//密码
	 * email:xxx,//邮箱 phone:xxx//手机
	 * 
	 * }//所有参数都可缺省,全部缺省情况默认密码12345678
	 * 
	 * 返回:{ status:xxx, //0: 注册失败 200: 注册成功 userid:xxx //返回新的用户id }
	 */
	public String registerReader(String userName, int sex, int age, String password, String email, String phone) {

		String userId = null;

		// 判断password为null或"",则使用默认密码12345678
		if (StringUtil.isEmpty(password)) {
			password = "12345678";
		}

		// 插入
		String sql_insert = "INSERT INTO `mandarin`.`user` (`userName`, `sex`,`age`,`password`,`email`,`phone`,`type`) VALUES (?,?,?,?,?,?,?);";
		Object[] param_insert = new Object[7];
		param_insert[0] = userName;
		param_insert[1] = sex;
		param_insert[2] = age;
		param_insert[3] = password;
		param_insert[4] = email;
		param_insert[5] = phone;
		param_insert[6] = "reader";
		int flag = JDBCUtil.insDelUpd(sql_insert, param_insert);

		// 成功,则查询最后一行的行号,即为新注册的账号userId
		if (flag > 0) {
			String sql_select = "SELECT * FROM mandarin.user;";
			ResultSet rs = JDBCUtil.select(sql_select);
			try {
				while (rs.next()) {
					userId = "" + rs.getInt("userId");
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return userId;

	}

	/**
	 * 获得读者的信息
	 * 
	 * @param account 读者账号
	 * 
	 *                Reader先为null,这样如果成功获取了数据返回创建好的Reader 失败了就返回null。
	 */
	public User getReader(int userId) {
		User reader = null;

		String sql = "select * from	user where userid = ?";

		Object[] param = new Object[1];
		param[0] = userId;
		ResultSet rs = JDBCUtil.select(sql, param);
		try {
			if (rs.next()) {
				reader = new User();
				reader.setUserId(rs.getInt("userId"));
				reader.setPassword(rs.getString("password"));
				reader.setUserName(rs.getString("userName"));
				reader.setAge(rs.getInt("age"));
				reader.setSex(rs.getInt("sex"));
				reader.setEmail(rs.getString("email"));
				reader.setPhone(rs.getString("phone"));
				reader.setType("reader");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return reader;
	}

	/**
	 * 编辑读者信息
	 * 
	 * @param 传入一个Reader
	 */
	public boolean editReader(User reader) {
		String sql = "UPDATE `mandarin`.`user` SET `password` = ?, `userName` = ?, `age`,`sex`,`email`,`phone` = ? WHERE (`userId` = ? and `type` = ?);";
		Object[] param = new Object[8];
		param[0] = reader.getPassword();
		param[1] = reader.getUserName();
		param[2] = reader.getAge();
		param[3] = reader.getSex();
		param[4] = reader.getEmail();
		param[5] = reader.getPhone();
		param[6] = reader.getUserId();
		param[7] = reader.getType();
		int flag = JDBCUtil.insDelUpd(sql, param);

		// 成功
		if (flag > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除读者
	 * 
	 * @param userId 读者账号
	 */
	public boolean deleteReader(int userId) {
		String sql = "DELETE from `mandarin`.`user`	where userId = ?;";
		Object[] param = new Object[1];
		param[0] = userId;
		int flag = JDBCUtil.insDelUpd(sql, param);

		// 成功
		if (flag > 0) {
			return true;
		} else {
			return false;
		}
	}
}
发布了461 篇原创文章 · 获赞 183 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/sandalphon4869/article/details/105267421