Java之DBUtils(实例)

7 篇文章 0 订阅
4 篇文章 0 订阅

DBUtils

  • apache提供的开源类库:工具类 对jdbc简单的封装

  • commons-dbutils-1.7.jar 核心jar包

  • 执行对象:QueryRunner

  • ResultSetHandler:处理程序 接口

  • 需要将查询某条记录封装成对象 :BeanHandler<?>

  • 需要将查询的多条记录(查询所有)封装List集合对象 :BeanListHandler<?>

  • 查询的单行单列的数据:查询总记录数ScalarHandler<>

上代码

需求 数据库有一张user表 使用Druid连接数据库 使用DBUtils对user表进行增删改查 查询结果封装到User实体内

Druid封装成的工具类

public class DriudUtils {

	private static DataSource ds;
	
	private DriudUtils() {}
	
	static {
		InputStream in = DriudUtils.class.getClassLoader().getResourceAsStream("druid.properties");
		Properties prop = new Properties();
		try {
			prop.load(in);
			ds = DruidDataSourceFactory.createDataSource(prop);
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static DataSource getDataSource() {
		return ds;
	}
	
	public static Connection getConnection() {
		Connection conn;
		try {
			conn = ds.getConnection();
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void close(ResultSet rs,Connection conn,PreparedStatement ps) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(ps!=null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void close(Connection conn,PreparedStatement ps) {
		close(null, conn, ps);
	}
	
}

User实体

public class User {

	private int id;
	private String username;
	private String password;
	private String email;
	private Date brithday;
	private String address;
	public User(int id,String username, String password, String email, Date brithday, String address) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.email = email;
		this.brithday = brithday;
		this.address = address;
	}
	public User() {
		super();
	}
	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 getBrithday() {
		return brithday;
	}
	public void setBrithday(Date brithday) {
		this.brithday = brithday;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email
				+ ", brithday=" + brithday + ", address=" + address + "]";
	}


}

UserDao

public interface UserDao {
	//添加
	public void insertUser(User u);
	//根据id删除
	public void deleteUserById(int id);
	//根据id查找
	public User selectUserById(int id);
	//查找所有
	public List<User> selectAllUsers();
	//查找总记录
	public long selectCount();
}

UserDaoImpl

public class UserDaoImpl implements UserDao{

	private static QueryRunner qr = new QueryRunner(DriudUtils.getDataSource());
	
	@Override
	public void insertUser(User u) {
		String sql = "insert into user (username,password,email,birthday,address)value(?,?,?,?,?)";
		try {
			int count = qr.update(
								sql,
								u.getUsername(),
								u.getPassword(),
								u.getEmail(),
								u.getBrithday(),
								u.getAddress());
			if(count>0) {
				System.out.println("插入成功");
			}else {
				System.out.println("插入失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void deleteUserById(int id) {
		String sql = "delete from user where id = ?";
		
		try {
			int count = qr.update(sql, id);
			if(count>0) {
				System.out.println("插入成功");
			}else {
				System.out.println("插入失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public User selectUserById(int id) {
		String sql = "select * from user where id = ?";
		
		try {
			User u = qr.query(sql, new BeanHandler<User>(User.class), id);
			return u;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public List<User> selectAllUsers() {
		String sql = "select * from user;";
		
		try {
			List<User> lists = qr.query(sql, new BeanListHandler<User>(User.class));
			return lists;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	@Override
	public long selectCount() {
		String sql = "select count(*) from user;";
		
		try {
			long count = qr.query(sql, new ScalarHandler<Long>());
			return  count;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return -1;
	}

}
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.parddu.dao; import java.io.IOException; import java.sql.*; import java.util.Properties; /** * 数据库功能类 * @author parddu * @version Sep 29, 2010 9:49:31 AM */ class DButil { private String driver=null; //驱动 private String dbName=null; //数据库名 private String host=null; //主机名 private String point=null; //端口 private String userName=null; //登录帐号 private String userPass=null; //登录密码 private static DButil info = null; private DButil(){} /** * 初始化方法,加载数据库连接信息 * @throws IOException */ private static void init() throws IOException{ Properties prop = new Properties(); prop.load(DButil.class.getResourceAsStream("/db_config.properties")); info = new DButil(); info.driver = prop.getProperty("driver"); info.dbName = prop.getProperty("dbName"); info.host = prop.getProperty("host"); info.point = prop.getProperty("point"); info.userName = prop.getProperty("userName"); info.userPass = prop.getProperty("userPass"); } /** * 得到数据库连接对象 * @return 数据库连接对象 */ static Connection getConn(){ Connection conn=null; if(info == null){ try { init(); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } if(info!=null){ try { Class.forName(info.driver); String url="jdbc:sqlserver://" + info.host + ":" + info.point + ";databaseName=" + info.dbName; conn=DriverManager.getConnection(url,info.userName,info.userPass); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } else{ throw new RuntimeException("读取数据库配置信息异常!"); } return conn; } /** * 关闭查询数据库访问对象 * @param rs 结果集 * @param st 上下文 * @param conn 连接对象 */ static void closeConn(ResultSet rs, Statement st,Connection conn){ try { rs.close(); } catch (Exception e) {} try { st.close(); } catch (Exception e) {} try { conn.close(); } catch (Exception e) {} } /** * 关闭增、删、该数据库访问对象 * @param st 上下文对象 * @param conn 连接对象 */ static void closeConn(Statement st ,Connection conn){ try{ st.close(); conn.close(); }catch(Exception e){} } }
ThreadLocal是Java中的一个线程局部变量,它可以为每个线程提供独立的变量副本,使得每个线程都可以独立地修改自己所拥有的变量副本,而不会影响其他线程的副本。DBUtils是一个开源的数据库操作工具类库,它封装了JDBC的操作细节,简化了数据库操作的代码。 当ThreadLocal与DBUtils结合使用时,可以实现在多线程环境下,每个线程都拥有独立的数据库连接,避免了线程间的资源竞争和并发访问的问题。 下面是一个ThreadLocal与DBUtils结合使用的示例: ```java import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; public class DBUtilsExample { private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<>(); public static void main(String[] args) { // 初始化数据源 DataSource dataSource = ...; // 创建查询器 QueryRunner queryRunner = new QueryRunner(dataSource); try { // 获取数据库连接 Connection connection = dataSource.getConnection(); // 将连接保存到ThreadLocal中 connectionHolder.set(connection); // 在当前线程中执行数据库操作 User user = queryRunner.query("SELECT * FROM user WHERE id = ?", new BeanHandler<>(User.class), 1); System.out.println(user); } catch (SQLException e) { e.printStackTrace(); } finally { // 关闭数据库连接 Connection connection = connectionHolder.get(); if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } // 清除ThreadLocal中的连接 connectionHolder.remove(); } } } ``` 在上述示例中,我们通过ThreadLocal将数据库连接保存在每个线程的独立副本中。这样,在每个线程中执行数据库操作时,都可以从ThreadLocal中获取到独立的数据库连接,而不会受到其他线程的影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值