Common Dbutils是操做數據庫的組件,對傳統操做數據庫的類進行二次封裝,能夠把結果集轉化成List。java
主要方法:mysql
DbUtils類:啓動類sql
ResultSetHandler接口:轉換類型接口數據庫
MapListHandler類:實現類,把記錄轉化成Listapache
BeanListHandler類:實現類,把記錄轉化成List,使記錄爲JavaBean類型的對象ui
Qrery Runner類:執行SQL語句的類this
創建三個Java文件url
命名爲BeanListExample.javaspa
Guestbook.javacode
MapListExample.java
源碼:
BeanListExample.java
Code
package com.sy;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
public class BeanListExample {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/people";
String jdbcDriver = "com.mysql.jdbc.Driver";
String user = "root";
String password = "hicc";
DbUtils.loadDriver(jdbcDriver);
try {
conn = DriverManager.getConnection(url, user, password);
QueryRunner qr = new QueryRunner();
List results = (List) qr.query(conn, "select id,name from guestbook", new BeanListHandler(Guestbook.class));
for (int i = 0; i < results.size(); i++) {
Guestbook gb = (Guestbook) results.get(i);
System.out.println("id:" + gb.getId() + ",name:" + gb.getName());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
}
Guestbook.java
Code
package com.sy;
public class Guestbook {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MapListExample.java
Code
package com.sy;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class MapListExample {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/people";
String jdbcDriver = "com.mysql.jdbc.Driver";
String user = "root";
String password = "hicc";
DbUtils.loadDriver(jdbcDriver);
try {
conn = DriverManager.getConnection(url, user, password);
QueryRunner qr = new QueryRunner();
List results = (List) qr.query(conn, "select id,name from guestmessage", new MapListHandler());
for (int i = 0; i < results.size(); i++) {
Map map = (Map) results.get(i);
System.out.println("id:" + map.get("id") + ",name:" + map.get("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
}
使用組建好須要添加commons-dbutils-1.1.jar和mysql-connector-java-5.1.6-bin.jar兩個jar包。
配置完畢!!!