今天老师讲了一下如何简化后台编程,给我们挑了一个数据库后台的框架——C3P0Utils。一直是自己写的数据库操作代码,除了一些比较难的会用到框架,像数据库这种基
本上就自己写了。现在回过头来看,以前虽然是把基本功打扎实了,但是重复造了N多个轮子,而且有代码时候老是出一些小毛病(要么就是这里忘记初始化,要么就是那里忘记
捕捉异常,或者就是这个包没导进来。。。。。),浪费了自己N多时间在找Bug上面,很多时候本来热情澎湃的自己都被这些低级的毛病给折磨的要死。
虽然很多人会说上面那些错误是你粗心大意了。好吧,我承认我是有点粗心,但是谁没有个大意的时候,谁能保证在任何情况下都不会出错,谁能保证在代码量巨大的情况
下,所有东西都自己写?懂得了原理后,用人家的框架就会节省很多时间。就像牛顿说的:”站在巨人的肩膀上“,这样才能飞的更高。根本不用重复造轮子,时间不是多的没地
方用的,应该用到更有价值的地方去。
出于比较的想法,我把平常自己写的跟用框架之后的做一个对比:
一、平常自己写的:
package com.david_kuper_ma.utils; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public final class JdbcUtils { //连接数据库的参数 private static String url = null; private static String user = null; private static String driver = null; private static String password = null; private JdbcUtils () { } private static JdbcUtils instance = null; public static JdbcUtils getInstance() { if (instance == null) { synchronized (JdbcUtils.class) { if (instance == null) { instance = new JdbcUtils(); } } } return instance; } //配置文件 private static Properties prop = new Properties(); //注册驱动 static { try { //利用类加载器读取配置文件 InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("dbInfo.properties"); prop.load(is); url = prop.getProperty("url"); user = prop.getProperty("user"); driver = prop.getProperty("driver"); password = prop.getProperty("password"); Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //该方法获得连接 public Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } //释放资源 public void free(Connection conn, Statement st, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { } } if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } finally { } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.david_kuper_ma.impl; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import com.david_kuper_ma.dao.DAO; import com.david_kuper_ma.entity.User; import com.david_kuper_ma.utils.JdbcUtils; import com.mysql.jdbc.PreparedStatement; public class DaoImplByJdbcUtils implements DAO { private String sql = null; PreparedStatement pstmt = null; ResultSet rSet = null; @Override public void addUser(User user) { // TODO Auto-generated method stub sql = "insert into user (username,password,email) values(?,?,?)"; Connection connection = null; try { connection = JdbcUtils.getInstance().getConnection(); System.out.println("连接成功"); pstmt = (PreparedStatement) connection.prepareStatement(sql); pstmt.setString(1, user.getUsername()); pstmt.setString(2, user.getPassword()); pstmt.setString(3, user.getEmail()); int count = pstmt.executeUpdate(); if (count > 0) { System.out.println("插入成功!"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { JdbcUtils.getInstance().free(connection,pstmt,null); } } @Override public void updateUser(User user) { // TODO Auto-generated method stub } @Override public void deleteUser(int id) { // TODO Auto-generated method stub } @Override public User queryByNameAndPwd(String username, String password) { // TODO Auto-generated method stub return null; } @Override public List<User> queryAll() { // TODO Auto-generated method stub return null; } }
driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/db_training user=root password=root
二、用了C3P0Utils框架后:
<pre name="code" class="java">package com.david_kuper_ma.utils; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Utils { private static DataSource dataSource = new ComboPooledDataSource(); public static DataSource getDatasource(){ return dataSource; } }
package com.david_kuper_ma.impl; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import com.david_kuper_ma.dao.DAO; import com.david_kuper_ma.entity.User; import com.david_kuper_ma.utils.C3P0Utils; public class DaoImplByDBUtils implements DAO { QueryRunner qr = new QueryRunner(C3P0Utils.getDatasource()); /** * 就一行代码就完成了插入的操作 */ @Override public void addUser(User user) { // TODO Auto-generated method stub String sql = "insert into user(username,password,email) values(?,?,?)"; Object[] params = new Object[]{user.getUsername(),user.getPassword(),user.getEmail()}; try { qr.update(sql,params); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void updateUser(User user) { // TODO Auto-generated method stub String sql = "update user set username = ? where id = ?"; Object[] params = new Object[]{user.getUsername(),user.getId()}; try { qr.update(sql, params); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void deleteUser(int id) { // TODO Auto-generated method stub } @Override public User queryByNameAndPwd(String username, String password) { // TODO Auto-generated method stub return null; } @Override public List<User> queryAll() { // TODO Auto-generated method stub return null; } }
配置文件(c3p0-config.xml):
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <!-- 数据库连接属性 --> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/db_training</property> <property name="user">root</property> <property name="password">root</property> <!-- 连接池相应的属性 --> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> </c3p0-config>