JDBCTools 第一个版本
JDBCToolV1:
package com.dgd.test; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; public class JDBCToolsV1 { public static DataSource ds; //静态代码块,创建数据库连接池 static { try { Properties p=new Properties(); p.load(JDBCToolsV1.class.getClassLoader().getResourceAsStream("druid.properties")); ds= DruidDataSourceFactory.createDataSource(p); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection(){ //方式1: DriverManger.getConnection(); //方式2: 数据库连接池, ds.getConnection(); try { return ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); return null; } } public static void free( Connection conn){ try { if(conn!=null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } //增删改,不能处理事务 public static int update1(String sql, Object...args) throws SQLException { //获取连接 Connection conn= getConnection(); //创建PreparedStatement对象 PreparedStatement ps= conn.prepareStatement(sql); //设置 ? if(args!=null&& args.length>0) { for (int i = 0; i <args.length ; i++) { ps.setObject(i+1,args[i]); } } //执行sql int len=ps.executeUpdate(); //关闭 ps.close(); free(conn); return len; }
//处理事务的公共部分 public static int update2(Connection conn, String sql, Object... args) throws SQLException { PreparedStatement ps=conn.prepareStatement(sql); if(args!=null && args.length>0) { for (int i = 0; i <args.length ; i++) { ps.setObject(i+1,args[i]); } } int len=ps.executeUpdate(); ps.close(); return len; } }
Test:
package com.dgd.test; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; public class TestJDBCToolV1 { @Test public void test1(){ try { String sql="INSERT INTO COURSE VALUES(NULL,?)"; int len=JDBCToolsV1.update1(sql,"天文"); System.out.println(len>0?"成功":"失败"); } catch (SQLException e) { e.printStackTrace(); } } @Test //处理事务,不能使用update1,因为update1中每次都是获取一个数据库连接对象,不能保证事务的ACID public void test() throws SQLException { String sql1="INSERT INTO COURSE VALUES(NULL,?)"; String sql2="INSERT INTO COURSE VALUES(NULL,?)"; Connection conn= JDBCToolsV1.getConnection(); conn.setAutoCommit(false); try { int len1=JDBCToolsV1.update2(conn,sql1,"美术"); int len2=JDBCToolsV1.update2(conn,sql2,"体育"); if(len1>0 && len2>0) { conn.commit(); } else { conn.rollback(); } } catch (SQLException e) { conn.rollback(); } conn.setAutoCommit(true); JDBCToolsV1.free(conn); } }