日期:2014-05-16 浏览次数:20505 次
package www.libinxuan.dbutils; 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; public class BeanListExample { public static void main(String[] args){ DbUtils.loadDriver("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/usertable" ; String sql = "select * from user"; try { Connection conn = DriverManager.getConnection(url,"root","root"); QueryRunner qr = new QueryRunner(); List results = (List)qr.query(conn, sql, new BeanListHandler<User>(User.class)); DbUtils.close(conn); User user = null; for(int i=0; i<results.size(); i++){ user = (User)results.get(i); System.out.println("用户名: " + user.getUsername()); System.out.println("密码: " + user.getPassword()); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }?Map
package www.libinxuan.dbutils; 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.MapListHandler; public class MapListExample { public static void main(String[] args){ DbUtils.loadDriver("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/usertable" ; String sql = "select * from user"; try { Connection conn = DriverManager.getConnection(url,"root","root"); QueryRunner qr = new QueryRunner(); List results = (List)qr.query(conn, sql, new MapListHandler()); DbUtils.close(conn); for(int i=0; i<results.size(); i++){ Map map = (Map)results.get(i); System.out.println("用户名: " + map.get("username")); System.out.println("密码: " + map.get("password")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }?User类
package www.libinxuan.dbutils; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }?