封装JDBCUtil工具

封装JDBC

一.准备数据

1.创建表及数据库

-- 若存在数据库mydb则删除
DROP DATABASE IF EXISTS mydb;
-- 创建数据库mydb
CREATE DATABASE mydb;
-- 选择数据库mydb
USE mydb;

-- 创建user表
CREATE TABLE user(
		id INT PRIMARY KEY AUTO_INCREMENT,
		username VARCHAR(40),
		password VARCHAR(40),
		email VARCHAR(40),
		birthday DATE
);

2.插入数据

-- 插入数据
INSERT INTO user(username,password,email,birthday)  VALUES ('lili','123456','[email protected]','1999-12-04');
INSERT INTO user(username,password,email,birthday)  VALUES ('dodo','565678','[email protected]','1997-10-07');
INSERT INTO user(username,password,email,birthday)  VALUES ('nxnx','246866','[email protected]','1992-11-11');
INSERT INTO user(username,password,email,birthday)  VALUES ('popo','246851','[email protected]','1999-11-22');

二.编写实体类User(JavaBean)

  • java.util.Date与java.sql.Date的关系
    • java.util.Date是父类
    • java.sql.Date是子类
package cn.com.demo04;

import java.util.Date;
public class User {
	private int id;
	private String username;
	private String password;
	private String email;
	private Date birthday;

	public User() {

	}

	public User(int id, String username, String password, String email, Date birthday) {
		this.id = id;
		this.username = username;
		this.password = password;
		this.email = email;
		this.birthday = birthday;
	}

	public int getId() {
		return id;
	}

	public void setId(int 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 Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email+ ", birthday=" + birthday + "]";
	}

}

三.JDBCUtils工具类

package cn.com.demo04;

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

public class JDBCUtils {
	// 加载驱动并建立数据库连接
	public static Connection getConnection() throws SQLException, ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver");
		String databaseUrl = "jdbc:mysql://localhost:3306/mydb";
		String username = "root";// 数据库用户名
		String password = "test";// 数据库密码
		Connection connection = DriverManager.getConnection(databaseUrl, username, password);
		return connection;
	}

	// 关闭数据库连接释放资源
	public static void release(Connection connection,Statement statement, ResultSet resultSet) {
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			connection = null;
		}
		
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			statement = null;
		}
		
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			resultSet = null;
		}
	}
}

四.UserDao

package cn.com.demo04;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class UserDao {
	
	// 添加用户
	public boolean insert(User user) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = JDBCUtils.getConnection();
			String sql = "INSERT INTO user(id,username,password,email,birthday) VALUES (?,?,?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, user.getId());
			preparedStatement.setString(2, user.getUsername());
			preparedStatement.setString(3, user.getPassword());
			preparedStatement.setString(4, user.getEmail());
			//请注意: setDate()方法第二参数类型为java.sql.Date
			Date date = new Date(user.getBirthday().getTime());
			preparedStatement.setDate(5, date);
			int num = preparedStatement.executeUpdate();
			if (num > 0) {
				return true;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(connection, preparedStatement,null);
		}
		return false;
	}

	// 删除用户
	public boolean delete(int userid) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = JDBCUtils.getConnection();
			String sql = "DELETE FROM user WHERE id=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, userid);
			int num = preparedStatement.executeUpdate();
			if (num > 0) {
				return true;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(connection, preparedStatement,null);
		}
		return false;
	}

	// 修改用户
	public boolean update(User user) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = JDBCUtils.getConnection();
			String sql = "UPDATE user SET username=? , password=? , email=? , birthday=? WHERE id=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, user.getUsername());
			preparedStatement.setString(2, user.getPassword());
			preparedStatement.setString(3, user.getEmail());
			//请注意: setDate()方法第二参数类型为java.sql.Date
			Date date = new Date(user.getBirthday().getTime());
			preparedStatement.setDate(4, date);
			preparedStatement.setInt(5, user.getId());
			int num = preparedStatement.executeUpdate();
			if (num > 0) {
				return true;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(connection, preparedStatement,null);
		}
		return false;
	}
	
	// 查找用户
	public User find(int userid) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			connection = JDBCUtils.getConnection();
			String sql = "SELECT * FROM user WHERE id = ?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, userid);
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				User user = new User();
				user.setId(resultSet.getInt("id"));
				user.setUsername(resultSet.getString("username"));
				user.setPassword(resultSet.getString("password"));
				user.setEmail(resultSet.getString("email"));
				//请注意:getDate()方法返回的类型为java.sql.Date
				user.setBirthday(resultSet.getDate("birthday"));
				return user;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(connection, preparedStatement,resultSet);
		}
		return null;
	}
	
	// 查询所有用户
	public ArrayList findAll() {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		ArrayList list = new ArrayList();
		try {
			connection = JDBCUtils.getConnection();
			String sql = "SELECT * FROM user";
			preparedStatement = connection.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				User user = new User();
				user.setId(resultSet.getInt("id"));
				user.setUsername(resultSet.getString("username"));
				user.setPassword(resultSet.getString("password"));
				user.setEmail(resultSet.getString("email"));
				//请注意:getDate()方法返回的类型为java.sql.Date
				user.setBirthday(resultSet.getDate("birthday"));
				list.add(user);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.release(connection, preparedStatement,resultSet);
		}
		return null;
	}
}

五.测试类

package cn.com.demo4;

import java.sql.Date;
import java.util.ArrayList;

public class TestJDBC {
	public static void main(String[] args) {
		UserDao userDao=new UserDao();
		//增加用户
		User user=new User();
		user.setId(5);
		user.setUsername("莉莉");
		user.setPassword("666666");
		user.setEmail("[email protected]");
		Date birthday=Date.valueOf("1997-07-01");
		user.setBirthday(birthday);
		userDao.insert(user);
		//修改用户
		user.setEmail("[email protected]");
		userDao.update(user);
		//查找用户
		User foundUser = userDao.find(user.getId());
		System.out.println(foundUser);
		//查找所有用户
		ArrayList userList = userDao.findAll();
		System.out.println(userList.size());
		//删除用户
		userDao.delete(user.getId());
	}

}

你可能感兴趣的:(JDBC,数据库,java)