dbutils使用

DBUtils包括3个包:
org.apache.commons.dbutils 
org.apache.commons.dbutils.handlers  //对数据进行处理
org.apache.commons.dbutils.wrappers
DBUtils 封装了对 JDBC 的操作,简化了 JDBC 操作。
 
举个简单的例子
public class infoBean
{
   private String username;
   private Integer age;
   private Float money;
   private Date usertime;
    
   public String getUsername()
  {
     return username;
  }
   public void setUsername(String username)
  {
     this.username = username;
  }
   public Integer getAge()
  {
     return age;
  }
   public void setAge(Integer age)
  {
     this.age = age;
  }
   public Float getMoney()
  {
     return money;
  }
   public void setMoney(Float money)
  {
     this.money = money;
  }
   public Date getUsertime()
  {
     return usertime;
  }
   public void setUsertime(Date usertime)
  {
     this.usertime = usertime;
  }
}
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

public class dbtest
{

    infoBean bean = new infoBean();

    BeanListHandler h = new BeanListHandler(bean.getClass());
    Connection connect = null;
    List result = new ArrayList();

     try
    {
      Class.forName( "com.mysql.jdbc.Driver");
      connect = DriverManager.getConnection(
           "jdbc:mysql://localhost/normaltest", "root", "root");

        
      QueryRunner run = new QueryRunner();

      result = (ArrayList) run.query(connect,
          "SELECT username,age,money,usertime FROM info", h);
    } catch (Exception e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return result;
  }
    
  public static void main(String [] args)
  {
    dbtest db = new dbtest();
    List result = db.getResult();
    for( int i = 0;i < result.size();i++)
    {
      infoBean bean = (infoBean)result.get(i);
      System.out.println(bean.getUsername());
      System.out.println(bean.getAge());
      System.out.println(bean.getMoney());
      System.out.println(bean.getUsertime());
      System.out.println("++++++++++++++++++++++++++++++++");
    }
    
  }
}

你可能感兴趣的:(java,jdbc,职场,DbUtils,休闲)