码迷,mamicode.com
首页 > 数据库 > 详细

jdbc封装DBUtil

时间:2018-09-04 19:48:58      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:override   gen   dstat   @param   enc   r.java   getc   lis   return   

1.编写实体类User

技术分享图片
public class User {
    private Integer id;
    private String username;
    private Integer age;
    private Date registerTime;  //mysql 使用时间戳

    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 Integer getAge() {
        return age;
    }

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

    public Date getRegisterTime() {
        return registerTime;
    }

    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username=‘" + username + ‘\‘‘ +
                ", age=" + age +
                ", registerTime=" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(registerTime) +
                ‘}‘;
    }
}
User.java

 

 

注意:java的Date对应数据库的timestamp

 

2.创建表

 CREATE TABLE users(
     id INT PRIMARY KEY AUTO_INCREMENT,
     username VARCHAR(20),
     age int,
     registerTime timestamp default now()
 )

 

技术分享图片

 

 3. 编写DBUtil

技术分享图片
package work;

import com.sun.rowset.CachedRowSetImpl;

import java.sql.*;

public class DbUtil {
    private Connection conn;
    private String url = "jdbc:mysql://localhost:3306/db_jdbc?characterEncoding=utf8";

    protected void setConnection() {
        //初始化conn
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "123");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询操作,返回缓存类,防止数据库连接关闭后无法访问ResultSet
     *
     * @param sql
     * @param params
     * @return
     */
    public CachedRowSetImpl executeQuery(String sql, Object... params) {
        if (conn == null) {
            setConnection();
        }
        PreparedStatement statement = null;
        ResultSet rs = null;
        CachedRowSetImpl rowset = null;
        try {
            statement = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                statement.setObject(i + 1, params[i]);
            }
            rs = statement.executeQuery();
            rowset = new CachedRowSetImpl();
            rowset.populate(rs);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            close();
        }
        return rowset;
    }

    /**
     * 执行删除、修改和添加操作
     * @param sql
     * @param params
     * @return
     */
    public int executeUpdate(String sql, Object... params) {
        int rs = 0;
        if (conn == null) {
            setConnection();
        }
        PreparedStatement statement = null;
        try {
            statement = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                statement.setObject(i + 1, params[i]);
            }
            rs = statement.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            close();
        }
        return rs;
    }


    protected void close() {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws SQLException {
        CachedRowSetImpl rowSet = new DbUtil().executeQuery("select * from student where id < ?", 10);
        while (rowSet.next()) {
            int id = rowSet.getInt("id");
            String name = rowSet.getString("name");
            String className = rowSet.getString("className");
            System.out.println("[id=" + id + ", name=" + name + ", className=" + className + "]");
        }
    }
}
DbUtil

 

 

4.UserDao.java

技术分享图片
package work;

import com.sun.rowset.CachedRowSetImpl;

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

public class UserDao {
    private DbUtil db;

    public DbUtil getDb() {
        return db;
    }

    public void setDb(DbUtil db) {
        this.db = db;
    }

    public UserDao(DbUtil db) {
        this.db = db;
    }

    /**
     * 查询所有user
     * @return
     */
    public List<User> getUsers(){
        List<User> users = new ArrayList<User>();
        String sql = "select * from users ";
        CachedRowSetImpl rowSet = db.executeQuery(sql);
        try {
            while(rowSet.next()){
                User user = new User();
                user.setId(rowSet.getInt("id"));
                user.setUsername(rowSet.getString("username"));
                user.setAge(rowSet.getInt("age"));
                user.setRegisterTime(rowSet.getTime("registerTime"));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    public int addUser(User user){
        int rs = 0;
        String sql = "insert into users (username, age, registerTime) values (?, ?, ?)";
        rs = db.executeUpdate(sql, user.getUsername(), user.getAge(), user.getRegisterTime());
        return rs;
    }

    /**
     * 删除user
     * @param id
     * @return
     */
    public int deleteUser(int id){
        int rs = 0;
        String sql = "delete from users where id = ? ";
        rs = db.executeUpdate(sql, id);
        return rs;
    }

    /**
     * 修改user
     * @param user
     * @return
     */
    public int updateUser(User user){
        int rs = 0;
        String sql = "update users set username = ?, age = ?, registerTime = ? where id = ? ";
        rs = db.executeUpdate(sql, user.getUsername(), user.getAge(), user.getRegisterTime(), user.getId());
        return rs;
    }
}
UserDao.java

 

jdbc封装DBUtil

标签:override   gen   dstat   @param   enc   r.java   getc   lis   return   

原文地址:https://www.cnblogs.com/zhuxiang1633/p/9587961.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!