借助DBUtils改进JDBCUtils工具类

闲来没事,借助commons-dbutils来改进了一下我的JDBC工具类

public class JdbcUtils {
	
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	private static QueryRunner qRunner;
	
	static {
		Properties p = new Properties();
		InputStream in = PropertiesTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
		try {
			//加载驱动
			p.load(in);
			driver = p.getProperty("driver");
			url = p.getProperty("url");
			username = p.getProperty("username");
			password = p.getProperty("password");
			Class.forName(driver);
			
			qRunner = new QueryRunner();
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	public static Connection getConnection() throws Exception {
		return DriverManager.getConnection(url, username, password);	 
	}
	
	public static int insert(String sql, Object...params) throws Exception {
		Connection conn = getConnection();
		return qRunner.update(conn, sql, params);
	}
	
	public static int delete(String sql, Object...params) throws Exception {
		Connection conn = getConnection();
		return qRunner.update(conn, sql, params);
	}
	
	public static  List query(String sql, Class clazz, Object...params) throws Exception {
		Connection conn = getConnection();
		List list = qRunner.query(conn, sql, new BeanListHandler(clazz), params);
		return list;
	}
	
	public static int update(String sql, Object...params) throws Exception {
		Connection conn = getConnection();
		return qRunner.update(conn, sql, params);
	}
	

}

其实使用过JDBC的都知道,增删改都会比较好操作,都可以统一为update就可以了,看我上面写的代码也能看出来,增删改都一样的,但是查询稍微麻烦一点点,借助泛型封装一下。

调用过程一下子就方便多了

        @Test
	public void insert() throws Exception {
		JdbcUtils.insert("insert into person values(null,?,?)", "西米",22);
	}
	
	@Test
	public void delete() throws Exception {
		JdbcUtils.delete("delete from person where id=?", 4);
	}
	
	@Test
	public void query() throws Exception {
		List list = JdbcUtils.query("select * from person", Person.class);
		System.out.println(list);
		List list1 = JdbcUtils.query("select * from person where id = ?", Person.class, 3);
		System.out.println(list1.get(0));
	}
	
	@Test
	public void update() throws Exception {
		JdbcUtils.delete("update person set age = ? where id=?", 3, 3);
	}

用久了mybatis,敲一敲JDBC,其实还是感悟挺深的。

你可能感兴趣的:(java)