Jakarta Commons的dbutils(http://commons.apache.org/dbutils/ )是很不错的,操作JDBC的工具类,举个例子如下,比较简单
mport java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
public class BeanutilsJDBCTest{
public static void main(String[] args) {
Connection conn = null;
String jdbcURL = "jdbc:mysql://127.0.0.1:3306/beanutildemo?useUnicode=true&characterEncoding=GBK";
String jdbcDriver = "com.mysql.jdbc.Driver";
try {
DbUtils.loadDriver(jdbcDriver);
// Username "root". Password "root"
conn = DriverManager.getConnection(jdbcURL, "root", "1979621");
QueryRunner qRunner = new QueryRunner();
System.out.println("***Using MapListHandler***");
//以下部分代码采用Map存储方式,可以采用Bean的方式代替进行处理
/** List lMap = (List) qRunner.query(conn,
"select title,authors from book", new MapListHandler());
//以下是处理代码,可以抽取出来
System.out.println("title ------------- authors ");
for (int i = 0; i < lMap.size(); i++) {
Map vals = (Map) lMap.get(i);
System.out.println(vals.get("title")+"-------------"+ vals.get("authors"));
}**/
List lBeans = (List) qRunner.query(conn," select title,authors from book ", new BeanListHandler(Book.class));
//以下是处理代码,可以抽取出来
System.out.println("title ------------- authors ");
for (int i = 0; i < lBeans.size(); i++) {
Book vals = (Book) lBeans.get(i);
System.out.println(vals.getTitle ()+"-------------"+ vals. getAuthors ());
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
2 还有个很典型的简单替代以前麻烦的用法哦
以前要这样:
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(strSql);
while (rs.next()) {
DeptVO dept = new DeptVO();
dept.setId(rs.getInt("id"));
dept.setName(rs.getString("name"));
dept.setEmail(rs.getString("email"));
dept.setTel(rs.getString("tel"));
dept.setAddress(rs.getString("address"));
list.add(dept);
}
现在可以这样了
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(strSql);
rsdc = new ResultSetDynaClass(rs,false);
dp = rsdc.getDynaProperties();
rows = rsdc.iterator();
while(rows.hasNext()){
DeptVO dept = new DeptVO();
DynaBean row = (DynaBean) rows.next();
PropertyUtils.copyProperties(dept ,row);
list.add(dept);
}