JDBC实现

package jdbc;

import java.lang.reflect.*;
import java.sql.*;
import com.mysql.jdbc.Driver;
public class PersistenceManager{
  private String dbUrl ="jdbc:mysql://localhost:3306/SAMPLEDB";
  private String dbUser="root";
  private String dbPwd="1234";

  public PersistenceManager() throw* **ception{
     //加载MySQL数据库驱动程序
     Class.forName("com.mysql.jdbc.Driver");
     DriverManager.registerDriver(new com.mysql.jdbc.Driver());
  }

  public Connection getConnection()throw* **ception{
      //获得一个数据库连接
      return java.sql.DriverManager.getConnection(dbUrl,dbUser,dbPwd);
  }

  public void save(Object object) throw* **ception {
    Connection con=null;
    PreparedStatement stmt=null;
    try {
      con=getConnection(); //获得数据库连接

      //开始一个数据库事务
      con.setAutoCommit(false);

      ObjectMapper om=new ObjectMapper(object);
      stmt=om.getInsertStatement(con);
      stmt.execute();

      //提交数据库事务
      con.commit();

    }catch(Exception e){
      e.printStackTrace();
      try{//如果出现异常,撤销整个事务
        con.rollback();
      }catch(SQLException sqlex){
        sqlex.printStackTrace(System.out);
      }
      throw e;
    }finally{
      try{
         stmt.close();
         con.close();
       }catch(Exception e){
         e.printStackTrace();
       }
    }
  }


  public Object load(Class classType,long id) throw* **ception {
    Connection con=null;
    PreparedStatement stmt=null;
    ResultSet rs=null;
    try {
      con=getConnection(); //获得数据库连接

      ObjectMapper om=new ObjectMapper(classType);
      om.setId(new Long(id));
      stmt=om.getSelectStatement(con);
      rs=stmt.executeQuery();

      Object object=om.parseResultSet(rs);
      return object;

    }finally{
      try{
         rs.close();
         stmt.close();
         con.close();
       }catch(Exception e){
         e.printStackTrace();
       }
    }
  }



  public void test()throw* **ception{
    Customer customer=new Customer("Tom",21);
    save(customer);

    customer=(Customer)load(Customer.class,1);
    System.out.println(customer.getId()+" "+customer.getName()+" "+customer.getAge());
  }

  public static void main(String args[])throw* **ception{
    new PersistenceManager().test();
  }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值