到目前為止,我們在使用QueryRunner時都是使用Connection
物件。 也可以使用資料源。 以下範例將演示如何在QueryRunner
和資料源的幫助下使用查詢讀取記錄。 這裡將從Employee
表中讀取一條記錄。
語法
QueryRunner queryRunner = new QueryRunner( dataSource );
Employee emp = queryRunner.query("SELECT * FROM employees WHERE first=?", resultHandler, "Sumit");
其中,
dataSource
- 組態了DataSource
物件。resultHandler
- ResultSetHandler
物件將結果集對映到Employee
物件。queryRunner
- 用於從資料庫讀取Employee
物件的QueryRunner
物件。以下是Employee.java
的內容。
public class Employee {
private int id;
private int age;
private String first;
private String last;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
以下是CustomDatasource.java
檔案的內容。
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
public class CustomDataSource {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/emp";
// Database credentials
static final String USER = "root";
static final String PASS = "admin";
private static DataSource datasource;
private static final BasicDataSource basicDataSource;
static {
basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName(JDBC_DRIVER);
basicDataSource.setUsername(USER);
basicDataSource.setPassword(PASS);
basicDataSource.setUrl(DB_URL);
}
public static DataSource getInstance() {
return basicDataSource;
}
}
以下是MainApp.java
檔案的內容。
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
public class MainApp {
public static void main(String[] args) throws SQLException {
DbUtils.loadDriver(JDBC_DRIVER);
QueryRunner run = new QueryRunner(CustomDataSource.getInstance());
ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(Employee.class);
Employee emp = queryRunner.query("SELECT * FROM employees WHERE id=?",
resultHandler, 103);
//Display values
System.out.print("ID: " + emp.getId());
System.out.print(", Age: " + emp.getAge());
System.out.print(", First: " + emp.getFirst());
System.out.println(", Last: " + emp.getLast());
}
}
完成建立原始檔後,執行該應用程式。 如果你的應用程式一切正常,它將列印下面的訊息。
ID: 103, Age: 33, First: Sumit, Last: Mittal