DBUtils資料查詢範例(使用ColumnListHandler)
前言
DBUtils提供ColumnListHandler用來封裝查詢結果集的某一欄的列表,並存放置List物件中,這樣說可能有些模糊,直接來看實際例子。
實作
以下實作一個簡單的例子。
DButilsSelectByColumnListHandlerDemo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| package tw.url.openjry;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import tw.url.openjry.conf.DataSourceConf;
/**
* DBUtils 資料查詢 (使用 ColumnListHandler)
*
* @author Art Yang
*
*/
public class DButilsSelectByColumnListHandlerDemo {
/**
* <p>主程式方法</p>
* <p>使用 ColumnListHandler 進行資料查詢並封裝查詢結果集的某一欄的 List<T> 列表</p>
*
* @param args 外部參數
* @throws ClassNotFoundException
* @throws SQLException
*/
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String sqlStmt = "select blogName, remark from blog";
QueryRunner queryRunner = new QueryRunner(DataSourceConf.getDataSource());
List<Object> listBlogs = queryRunner.query(sqlStmt, new ColumnListHandler<>(2));
listBlogs.forEach(System.out::println);
}
}
|
執行結果
1
2
3
4
5
6
7
8
9
10
11
| 生活記事、系統管理、程式設計、資料庫
生活記事、系統管理、程式設計、資料庫_0
生活記事、系統管理、程式設計、資料庫_1
生活記事、系統管理、程式設計、資料庫_2
生活記事、系統管理、程式設計、資料庫_3
生活記事、系統管理、程式設計、資料庫_4
生活記事、系統管理、程式設計、資料庫_5
生活記事、系統管理、程式設計、資料庫_6
生活記事、系統管理、程式設計、資料庫_7
生活記事、系統管理、程式設計、資料庫_8
生活記事、系統管理、程式設計、資料庫_9
|