DBUtils之查詢(二)
阿新 • • 發佈:2018-12-04
- 使用ColumnListHandler
public static void columnListHandler() throws SQLException { Connection con = MyJDBCUtiles.getConnection(); QueryRunner qr = new QueryRunner(); String sql = "select username,password from userinfo where age = ?"; //注意sql語句中的篩選項(username,password)一定要包括下列list中的引數項(username) Object [] param = {29}; List<Object> list = qr.query(con,sql,new ColumnListHandler<Object>("username"),param); //若沒有查詢到則list.size()=0 for (Object o : list){ System.out.println(o + "\t"); } }
- 結果
- 使用ScalarHandler
public static void scalarHandler() throws SQLException { Connection con = MyJDBCUtiles.getConnection(); String sql = "select count(*) from userinfo where age = ?"; QueryRunner qr = new QueryRunner(); Object [] param = {21}; long o = qr.query(con,sql,new ScalarHandler<Long>(),param); //若未查詢到,則o的值為0 System.out.println(o); }
- 結果