Apache Commons DbUtils 資料經由map對應取出
以下程式為資料取出放入List中(多筆)
try {
conn = DbUs.getConnection();==>database的連結字串
QueryRunner qr = new QueryRunner();
List results = (List) qr.query(conn, "select id,name from user", 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"));==>取對應的資料,資料型別為Object如要其他的動作須轉型.
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
以下程式為資料取出放入List中(單筆)
try {
conn = DbUs.getConnection();
QueryRunner qr = new QueryRunner();
String sql = "select shortname,custname from basobjectm where custno='" + mainSingle.getCustNo() + "' ";
Map result = (Map) qr.query(conn, sql, new MapHandler());
mainSingle.setCustName(result.get("custname").toString());
mainSingle.setCheckTitle(result.get("checktitle").toString());
conn.close();
} catch (Exception ex) {
try {
conn.close();
} catch (SQLException exl) {
}
}
try {
conn = DbUs.getConnection();==>database的連結字串
QueryRunner qr = new QueryRunner();
List results = (List) qr.query(conn, "select id,name from user", 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"));==>取對應的資料,資料型別為Object如要其他的動作須轉型.
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
以下程式為資料取出放入List中(單筆)
try {
conn = DbUs.getConnection();
QueryRunner qr = new QueryRunner();
String sql = "select shortname,custname from basobjectm where custno='" + mainSingle.getCustNo() + "' ";
Map result = (Map) qr.query(conn, sql, new MapHandler());
mainSingle.setCustName(result.get("custname").toString());
mainSingle.setCheckTitle(result.get("checktitle").toString());
conn.close();
} catch (Exception ex) {
try {
conn.close();
} catch (SQLException exl) {
}
}
留言
張貼留言