jdbc封装DBUtil
Posted fight139
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jdbc封装DBUtil相关的知识,希望对你有一定的参考价值。
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) + \'}\'; } }
注意: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.*; import java.util.HashMap; import java.util.Map; 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 */ //Object ... public CachedRowSetImpl executeQuery(String sql, Map<Integer, Object> params) { if (conn == null) { setConnection(); } PreparedStatement statement = null; ResultSet rs = null; CachedRowSetImpl rowset = null; try { statement = conn.prepareStatement(sql); if (params != null) { for (int i = 0; i < params.size(); i++) { statement.setObject(i + 1, params.get(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, Map<Integer, Object> params) { int rs = 0; if (conn == null) { setConnection(); } PreparedStatement statement = null; try { statement = conn.prepareStatement(sql); if(params!=null){ for (int i = 0; i < params.size(); i++) { statement.setObject(i + 1, params.get(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 < ?", new HashMap<Integer, Object>(){{put(0,5);}}); 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 + "]"); } } }
4.UserDao.java
package work; import com.sun.rowset.CachedRowSetImpl; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; 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, null); 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, new HashMap<Integer, Object>(){{ put(0, user.getUsername()); put(1, user.getAge()); put(2, 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, new HashMap<Integer, Object>(){{put(0, 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, new HashMap<Integer, Object>(){{ put(0, user.getUsername()); put(1, user.getAge()); put(2, user.getRegisterTime()); put(3, user.getId()); }}); return rs; } }
以上是关于jdbc封装DBUtil的主要内容,如果未能解决你的问题,请参考以下文章