Apache组件commons的DbUtils的用法实例

来源:互联网 发布:mac os 磁盘分区 编辑:程序博客网 时间:2024/04/27 22:02

1 代码要连接数据库是可以跑通的,可是本人真心表示这个封装的太垃圾,远不及自己写的顺手,不建议再学一套db连接的方法,这个感觉写的还有点复杂,不好用,不推荐

package com.commons.dbutils;import java.util.*;import java.util.logging.*;import java.sql.*;import org.apache.commons.dbutils.*;import org.apache.commons.dbutils.handlers.*;public class DbUtilsTest {public static void main(String[] args) throws Exception {DbUtilsTest test = new DbUtilsTest();for (int i = 0; i < 1; i++) {test.testQuery1();test.testQuery2();test.testUpdate();}}public void testQuery1() {try {QueryRunner qr = new QueryRunner();ResultSetHandler rsh = new ArrayListHandler();String strsql = "select * from test1";ArrayList result = (ArrayList) qr.query(getConnection(), strsql,rsh);// System.out.print("");} catch (Exception ex) {ex.printStackTrace(System.out);}}public void testQuery2() {try {QueryRunner qr = new QueryRunner();ResultSetHandler rsh = new MapListHandler();String strsql = "select * from test1";ArrayList result = (ArrayList) qr.query(getConnection(), strsql,rsh);for (int i = 0; i < result.size(); i++) {Map map = (Map) result.get(i);// System.out.println(map);}// System.out.print("");} catch (Exception ex) {ex.printStackTrace(System.out);}}public void testUpdate() {try {QueryRunner qr = new QueryRunner();ResultSetHandler rsh = new ArrayListHandler();String strsql = "insert test1(page ,writable ,content)values('ttt','ttt','faskldfjklasdjklfjasdklj')";qr.update(getConnection(), strsql);// System.out.print("");} catch (Exception ex) {ex.printStackTrace(System.out);}}private Connection getConnection() throws InstantiationException,IllegalAccessException, ClassNotFoundException, SQLException {String strDriver = "com.mysql.jdbc.Driver";String strUrl = "jdbc:mysql://localhost:3306/test";String strUser = "root";String strPass = "root";Class.forName(strDriver).newInstance();return DriverManager.getConnection(strUrl, strUser, strPass);}}


原创粉丝点击