DButils實現增刪改sql
/** * 測試DButils的增刪改 */ public class DBUtilsTest { /** * DButils 添加 */ @Test public void testadd(){ try{ QueryRunner qr = new QueryRunner(); String sql = "insert into t1 value(?,?)"; Object[] params = {9,"hhh"}; Connection conn = C3P0utils.getConnection(); int rows = qr.update(conn,sql,params); if (rows > 0) { System.out.println("添加成功!"); } else { System.out.println("添加失敗!"); } }catch (SQLException e){ throw new RuntimeException(e); } } /** * DButils 更改 */ @Test public void testupdate(){ try{ QueryRunner qr = new QueryRunner(); String sql = "update t1 set name=? where id = ?"; Object[] params = {"sxf",9}; Connection conn = C3P0utils.getConnection(); int rows = qr.update(conn,sql,params); if (rows > 0) { System.out.println("修改爲功!"); } else { System.out.println("修改失敗!"); } }catch (SQLException e){ throw new RuntimeException(e); } } /** * DButils 刪除 */ @Test public void testdel(){ try{ QueryRunner qr = new QueryRunner(); String sql = "delete from t1 where id = ?"; Object[] params = {7}; Connection conn = C3P0utils.getConnection(); int rows = qr.update(conn,sql,params); if (rows > 0) { System.out.println("刪除成功!"); } else { System.out.println("刪除失敗!"); } }catch (SQLException e){ throw new RuntimeException(e); } } }
DButils 查詢 測試
BeanListHandler 查詢全部裝置list
BeanHandler 指定第一天查詢信息
ScalarHandler 用於單數據操做
public class DBUtilsTest2 { /** * 查詢全部 */ @Test public void testQueryAll() { try{ QueryRunner qr = new QueryRunner(); String sql = "select * from t1"; Connection conn = C3P0utils.getConnection(); List<user> users = qr.query(conn,sql,new BeanListHandler<user>(user.class)); for(user u:users){ System.out.println(u.getId() + " : " + u.getName()); } }catch (SQLException e){ throw new RuntimeException(e); } } /* * 根據id查詢用戶方法 */ @Test public void testQueryUserById() { try { // 1.獲取核心類queryRunner QueryRunner qr = new QueryRunner(C3P0utils.getDataSource()); // 2.編寫sql語句 String sql = "select * from t1 where id=?"; //3.爲佔位符設置值 Object[] params = {5}; // 4.執行查詢操做 user user = qr.query(sql, new BeanHandler<user>(user.class), params); System.out.println(user.getId() + " : " + user.getName()); } catch (SQLException e) { throw new RuntimeException(e); } } /* * 根據全部用戶的總個數 */ @Test public void testQueryCount() { try { // 1.獲取核心類queryRunner QueryRunner qr = new QueryRunner(C3P0utils.getDataSource()); // 2.編寫sql語句 String sql = "select count(*) from t1"; // 4.執行查詢操做 Long count = (Long) qr.query(sql, new ScalarHandler()); System.out.println(count); } catch (SQLException e) { throw new RuntimeException(e); } } }