DBUtils資料查詢範例(使用MapHandler)
前言
DBUtils可以使用MapHandler做為取得資料的結果集,Key則為欄位名稱(可使用AS重新命名),而Value則為欄位值,使用起來相當簡便。
實作
以下進行簡單的示範。
Java程式碼
DBUtilsSelectByMapHandlerDemo.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
37
|
package tw.url.openjry;
import java.sql.SQLException;
import java.util.Map;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import tw.url.openjry.conf.DataSourceConf;
/**
* DBUtils 資料查詢 (使用 MapHandler)
*
* @author Art Yang
*
*/
public class DBUtilsSelectByMapHandlerDemo {
/**
* <p>主程式方法</p>
* <p>使用 MapHandler 進行資料查詢會返回封裝好 Key, Value 的 Map 物件,只用於單一結果查詢</p>
*
* @param args 外部參數
* @throws ClassNotFoundException
* @throws SQLException
*/
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String sqlStmt = "select * from blog where blogSeqNo = ?";
QueryRunner queryRunner = new QueryRunner(DataSourceConf.getDataSource());
Map<String, Object> result = queryRunner.query(sqlStmt, new MapHandler(), "1");
System.out.println(result);
}
}
|
執行結果
1
| {blogSeqNo=1, blogName=楊藝的洋溢生活, author=Art Yang, remark=生活記事、系統管理、程式設計、資料庫, createdTime=2019-05-01 13:40:57.0, updatedTime=null}
|