重构jdbc代码模拟用户登录功能

JdbcUtil.java

package com.jdbc.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class JdbcUtil {
	private static BasicDataSource dataSource = null;
	static{
		dataSource = new BasicDataSource();
		Properties prop = new Properties();
		try {
			prop.load(JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties"));
			String url = prop.getProperty("jdbc.url");
			String username = prop.getProperty("jdbc.username");
			String password = prop.getProperty("jdbc.password");
			String initialSizeStr = prop.getProperty("jdbc.initialSize");
			int initialSize = Integer.parseInt(initialSizeStr);
			String maxActiveStr = prop.getProperty("jdbc.maxActive");
			int maxActive = Integer.parseInt(maxActiveStr);
			String maxWaitStr = prop.getProperty("jdbc.maxWait");
			int maxWait = Integer.parseInt(maxWaitStr);
			try {
				Class.forName("com.mysql.jdbc.Driver");
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			dataSource.setUrl(url);
			dataSource.setUsername(username);
			dataSource.setPassword(password);
			dataSource.setInitialSize(initialSize);
			dataSource.setMaxActive(maxActive);
			dataSource.setMaxWait(maxWait);	
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	public static Connection getConn() throws SQLException{
		return dataSource.getConnection();
	}
	public static void close(Connection conn){
		if (conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) throws SQLException {
		System.out.println(dataSource.getUrl()+getConn());
	}
}

db.properties

jdbc.url=jdbc:mysql://localhost:3306/gjxfj?useSSL=true
jdbc.username=root
jdbc.password=root
jdbc.initialSize=20
jdbc.maxActive=100
jdbc.maxWait=5000

User.java

package com.jdbc.entity;

import java.io.Serializable;
import java.sql.Timestamp;
/**
 * 项目中实体类的开发
 * 一个实体数据表对应一个实体类
 * 1、定义一组private属性
 * 2、定义一组对应属性的setter和getter
 *    特殊的属性:只读属性
 * 3、定义一组构造器
 * 4、重写hashCode(),equals(),toString()
 * 5、实现Serializable接口
 *    Serializable可序列化标识接口
 */
public class User implements Serializable{

	private static final long serialVersionUID = 1L;
	private Integer id;
	private String username;
	private String password;
	private String email;
	private String phone;
	private Timestamp created;
	private Timestamp updated;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	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 Timestamp getCreated() {
		return new Timestamp(System.currentTimeMillis());
	}
	//返回系统当前时间
	public Timestamp getUpdated() {
		return new Timestamp(System.currentTimeMillis());
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + ", phone="
				+ phone + ", created=" + created + ", updated=" + updated + "]";
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	public User(Integer id, String username, String password, String email, String phone, Timestamp created,
			Timestamp updated) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.email = email;
		this.phone = phone;
		this.created = created;
		this.updated = updated;
	}
	public User() {
		super();
	}
	public User(Integer id, String username, String password, String email, String phone) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.email = email;
		this.phone = phone;
	}
	
}

BaseDao.java

package com.jdbc.dao.impl;

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

import javax.sql.rowset.CachedRowSet;
import com.jdbc.util.JdbcUtil;
import com.sun.rowset.CachedRowSetImpl;

public class BaseDao {
	public int update(String sql, Object... params) {
		int result = 0;
		Connection conn = null;
		try {
			conn = JdbcUtil.getConn();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i + 1, params[i]);
				}

			}
			result = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(conn);
		}
		return result;
	}

	public CachedRowSet findData(String sql, Object... params) {
		Connection conn = null;
		CachedRowSet crs = null;
		try {
			conn = JdbcUtil.getConn();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i + 1, params[i]);
				}
			}
			ResultSet rs = pstmt.executeQuery();
			crs = new CachedRowSetImpl();
			crs.populate(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(conn);
		}
		return crs;
	}
}

UserDaoImpl2.java

package com.jdbc.dao.impl;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.sql.rowset.CachedRowSet;
import com.jdbc.entity.User;

public class UserDaoImpl2 extends BaseDao {
	// 代码重构
	public int save(User user) {
		String sql = "insert into ajia_user(username,password,email,phone,created,updated) " + "values(?,?,?,?,?,?)";
		return update(sql, user.getUsername(), user.getPassword(), user.getEmail(), user.getPhone(), user.getCreated(),
				user.getUpdated());
	}

	public int updatePassword(String newPassword, Integer id) {
		String sql = "update ajia_user set password = ? where id = ?";
		return update(sql, newPassword, id);
	}

	public int updateUser(User user) {
		String sql = "update ajia_user set email = ?,phone = ?,updated = ? where id = ?";
		return update(sql, user.getEmail(), user.getPhone(), new Timestamp(System.currentTimeMillis()), user.getId());
	}

	public int delete(Integer id) {
		String sql = "delete from ajia_user where id = ?";
		return update(sql, id);
	}

	public boolean findByUsername(String username) throws SQLException {
		String sql = "select * from ajia_user where username = ?";
		boolean isUsed = false;
		CachedRowSet rs = findData(sql, username);
		while (rs.next()) {
			isUsed = true;
		}
		return isUsed;
	}

	public boolean findByPhone(String phone) throws SQLException {
		String sql = "select * from ajia_user where phone = ?";
		boolean isUsed = false;
		CachedRowSet rs = findData(sql, phone);
		while (rs.next()) {
			isUsed = true;
		}
		return isUsed;
	}

	public boolean findByEmail(String email) throws SQLException {
		String sql = "select * from ajia_user where email = ?";
		boolean isUsed = false;
		CachedRowSet rs = findData(sql, email);
		while (rs.next()) {
			isUsed = true;
		}
		return isUsed;
	}

	// 模仿登录
	public User findByUser(String username, String password) throws SQLException {
		String sql = "select * from ajia_user where username = ? and password = ?";
		User user = null;
		CachedRowSet rs = findData(sql, username, password);
		while (rs.next()) {
			user = mapper(rs);
		}
		return user;

	}
	//查询多条记录
	public List<User> findAll() throws SQLException{
		List<User> list = new ArrayList<User>();
		User user = null;
		String sql = "select * from ajia_user";
		CachedRowSet rs = findData(sql);
		while(rs.next()){
			user = mapper(rs);
			list.add(user);
		}
		return list;
	}
	// 映射记录与对象
	public User mapper(CachedRowSet rs) throws SQLException {
		User user = new User();
		user.setId(rs.getInt("id"));
		user.setUsername(rs.getString("username"));
		user.setPassword(rs.getString("password"));
		user.setEmail(rs.getString("email"));
		user.setPhone(rs.getString("phone"));
		return user;
	}
	public static void main(String[] args) throws SQLException {
		UserDaoImpl2 dao = new UserDaoImpl2();
		List<User> list = dao.findAll();
		for (User user : list) {
			System.out.println(user);
		}
	}
}



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页