package com.commonsbook.chap11; import org.apache.commons.dbutils.*; import org.apache.commons.dbutils.handlers.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.List; import java.util.Map; public class UseDbUtils { public static void main(String[] args) { Connection conn = null; String jdbcURL = "jdbc:mysql://127.0.0.1:3306/test"; String jdbcDriver = "com.mysql.jdbc.Driver"; try { DbUtils.loadDriver(jdbcDriver); //Username "root". Password "" conn = DriverManager.getConnection(jdbcURL, "root", ""); QueryRunner qRunner = new QueryRunner(); System.out.println("***Using MapListHandler***"); List lMap = (List) qRunner.query(conn, "SELECT StudId, Name FROM Student WHERE StudId IN (?, ?)", new String[] { "1", "2" }, new MapListHandler()); for (int i = 0; i < lMap.size(); i++) { Map vals = (Map) lMap.get(i); System.out.println("\tId >>" + vals.get("studid")); System.out.println("\tName >>" + vals.get("name")); } System.out.println("***Using BeanListHandler***"); List lBeans = (List) qRunner.query(conn, "SELECT StudId, Name FROM Student", new BeanListHandler(StudentBean.class)); for (int i = 0; i < lBeans.size(); i++) { StudentBean vals = (StudentBean) lBeans.get(i); System.out.println("\tId >>" + vals.getStudId()); System.out.println("\tName >>" + vals.getName()); } } catch (SQLException ex) { ex.printStackTrace(); } finally { DbUtils.closeQuietly(conn); } } } |