2007-09-03

封装jdbc

  • 这时是数据库的表:  
  •   
  • DROP DATABASE IF EXISTS `hibernate`;  
  • CREATE DATABASE `hibernate` ;  
  • USE `hibernate`;  
  • CREATE TABLE `person` (  
  •   `id` int(32) NOT NULL DEFAULT '0',  
  •   `name` varchar(20) NOT NULL,  
  •   `password` varchar(20) NOT NULL,  
  •   PRIMARY KEY (`id`)  
  • ) ENGINE=InnoDB DEFAULT CHARSET=gb2312;  
  •   
  •   
  • 1.首先我们先做一个接口,现在先不管它,等下你就知道他有什么用啦  
  •   
  • package com.dongguoh;  
  •   
  • import java.sql.*;  
  • /* 
  •  * 用匿名类的方式去运用这个接口 
  •  */  
  • public interface IStatementCallback {  
  •     public Object doInStatement(Statement stmt) throws RuntimeException,SQLException;  
  •       
  • }  
  •   
  • 2.而这里是最关键的,就是建一个Jdbc的模板方法,把那些经常要做的try{} catch{}都写在一个类里  
  •     免得以后每次都还去写。这就成啦代码复用.  
  •   
  • package com.dongguoh;  
  •   
  • import java.sql.*;  
  • /* 
  •  * 在这里我就不用Spring的注入啦,直接写个完整的 
  •  * 如果不会Spring的,也同样的像使用Spring中的JdbcTemplate类一样的使用. 
  •  * 如果你看过Spring的书,那么这个例子也是一个Spring的入门jdbc的好例子 
  •  *  
  •  * 而在这里我们的这个JdbcTemplate就成啦一个通用的方法,以后我们要SQL语句连接数据库的 
  •  * 时候不用每次都去写try{}catch{}啦,老那样写真的很烦,一次性就把它搞定啦 
  •  */  
  • public class JdbcTemplate {  
  •       
  •   
  •     public Object execute(IStatementCallback action) {  
  •         Connection conn = null;  
  •         Statement stmt = null;  
  •         Object result = null;         
  •         try {  
  •             conn=this.getConnection();  
  •             conn.setAutoCommit(false);            
  •             stmt=conn.createStatement();  
  •               
  •             //注意这一句  
  •             result=action.doInStatement(stmt);  
  •               
  •             conn.commit();  
  •             conn.setAutoCommit(true);             
  •         } catch (SQLException e) {  
  •             transactionRollback(conn);//进行事务回滚  
  •             e.printStackTrace();  
  •             throw new RuntimeException(e);  
  •         }finally{  
  •             this.closeStatement(stmt);  
  •             this.closeConnection(conn);  
  •         }  
  •   
  •         return result;  
  •     }  
  •       
  •     /* 
  •      * 当发生异常时进行事务回滚 
  •      */  
  •     private void transactionRollback(Connection conn){  
  •         if(conn!=null){  
  •             try {  
  •                 conn.rollback();  
  •             } catch (SQLException e) {  
  •                 // TODO Auto-generated catch block  
  •                 e.printStackTrace();  
  •             }  
  •         }  
  •           
  •     }  
  •     //关闭打开的Statement  
  •     private void closeStatement(Statement stmt){  
  •         if(stmt!=null){  
  •             try {  
  •                 stmt.close();  
  •                 stmt=null;  
  •             } catch (SQLException e) {  
  •                 e.printStackTrace();  
  •             }  
  •         }  
  •     }  
  •     //关闭打开的Connection   
  •     private void closeConnection(Connection conn){  
  •         if(conn!=null){  
  •             try {  
  •                 conn.close();  
  •                 conn=null;  
  •             } catch (SQLException e) {  
  •                 e.printStackTrace();  
  •             }  
  •         }  
  •     }  
  •   
  •     //取得一个Connction  
  •     private Connection getConnection() {          
  •         String driver = "com.mysql.jdbc.Driver";  
  •         String url = "jdbc:mysql://127.0.0.1/Hibernate";          
  •         Connection conn=null;  
  •         try {  
  •             Class.forName(driver);  
  •             conn = DriverManager.getConnection(url, "root""dongguoh");  
  •         } catch (ClassNotFoundException e) {  
  •             e.printStackTrace();  
  •         } catch (SQLException e) {  
  •             e.printStackTrace();  
  •         }  
  •         return conn;  
  •     }  
  •   
  • }  
  •   
  • 下面是我们的测试方法:  
  • package com.dongguoh;  
  •   
  • import java.sql.*;  
  •   
  • import junit.framework.TestCase;  
  •   
  • public class TestTemplate extends TestCase {  
  •   
  •     public void testJdbcTemplate(){  
  •         JdbcTemplate jt=new JdbcTemplate();  
  •         /* 
  •          * 因为IStatementCallback是一个接口,所以我们在这里直接用一个匿名类来实现 
  •          * 如果已经正确的插入啦一条数据的话 ,它会正确的返回一个 整数 1  
  •          * 而我们这里的stmt是从JdbcTemplate中传过来的 
  •          */  
  •         int count=(Integer)jt.execute(new IStatementCallback(){  
  •             public Object doInStatement(Statement stmt) throws RuntimeException, SQLException {  
  •   
  •                 String sql="INSERT INTO person VALUES(1,'dongguoh','123456')";  
  •                 int result=stmt.executeUpdate(sql);  
  •                 return new Integer(result);  
  •             }             
  •         });       
  •         System.out.println("Count: "+count);  
  •           
  •         /* 
  •          * 在这里我们就把刚刚插入的数据取出一个数据,直接输出来 
  •          *  
  •          */  
  •         jt.execute(new IStatementCallback(){  
  •             public Object doInStatement(Statement stmt) throws RuntimeException, SQLException {  
  •   
  •                 String sql="SELECT name,password FROM person WHERE id=1";  
  •                 ResultSet rs=null;  
  •                 rs=stmt.executeQuery(sql);  
  •                 if(rs.next()){  
  •                     System.out.println(rs.getString("name"));  
  •                     System.out.println(rs.getString("password"));  
  •                 }  
  •                 /* 
  •                  * 在这里就直接返回一个1啦,如果你愿意的话,你可以再写一个Person类 
  •                  * 在if语句中实例化它,赋值再把它返回 
  •                  */  
  •                 return new Integer(1);  
  •             }             
  •         });       
  •     }  
  • }  
  •   
  • 测试结果:  
  • Count: 1  
  • dongguoh  
  • 123456  
  •   
  • 如果你要用 PreparedStatement 的话,想传参数的话,再写一个接口来实现,再在JdbcTemplate重载一个方法  
  •     如public Object execute(IPreparedStatementCallback action,,Object[] objArray)再多传一个你要传递的参数数组, 
  • 评论
    发表评论

    您还没有登录,请登录后发表评论

    iorit2003
    搜索本博客
    我的相册
    499ddab3-84d3-357f-afb3-7ac85862e224-thumb
    100_0198.JPG
    共 3 张
    最近加入圈子
    存档
    最新评论