說明:本文非原生jdbc案例,經過DbUtils和C3p0實現對原生jsdc的簡單封裝。直接以案例開始php
一.前期準備html
*導入jar包java
mysql
*添加c3p0配置文件和jdbcutils工具類sql
▶c3p0-config.xml(文件名稱不能改變,且默認必須放在src目錄下)
數據庫
▶jdbcutils工具類app
package com.learn.utils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * 將增刪改查操做中重複代碼提取出來 */ public class JDBCUtils { //建立數據庫鏈接池對象 private static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); //獲取鏈接的方法 public static Connection getConnection() throws SQLException{ return comboPooledDataSource.getConnection(); } //提供數據庫鏈接池對象的方法 public static DataSource getDataSource(){ return comboPooledDataSource; } //釋放資源的方法 public static void release(ResultSet rs, Statement stmt, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs = null; } release(stmt, conn); } public static void release(Statement stmt, Connection conn) { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } stmt = null; } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } } }
▶建表、建實體類(表與實體類字段相對應)
框架
二.使用queryRunner實現增刪改查ide
*添加操做工具
*修改操做
*刪除操做
//DbUtils結合c3p0刪除====================================================================== String sql2="delete from contect where id=?"; try { int update = runner.update(sql2, "1"); System.out.println(update); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }
*查詢操做
▶ 自定義handler查詢
MyHandler
public class MyHandler implements ResultSetHandler<List<Contect>>{ @Override public List<Contect> handle(ResultSet rs) throws SQLException { //封裝數據,數據從Resultset中獲取 ArrayList<Contect> list = new ArrayList<Contect>(); while(rs.next()){ Contect contect = new Contect(); String name = rs.getString("cname"); contect.setCname(name); String sex = rs.getString("sex"); contect.setSex(sex); String tel = rs.getString("tel"); contect.setTel(tel); String address = rs.getString("address"); contect.setAddress(address); list.add(contect); } return list; } }
查詢
String sql3 ="select * from contect"; try { List<Contect> contectList = runner.query(sql3, new MyHandler()); System.out.println(contectList); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }
▶ResultSetHandler實現類介紹(由DBUtils框架給咱們提供使用)實現類的學習方式:
先測試,根據測試結果總結當前實現類的按照什麼樣的方式封裝數據(策略)
ArrayListHandler
String sql4 ="select * from contect"; try { List<Object[]> list = runner.query(sql4, new ArrayListHandler()); for (Object[] objects : list) { for (Object object : objects) { System.out.println(object); } System.out.println("------------------------------------"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }
BeanHandler
BeanListHandler
ScalarHandler