标签:dbutils
写一个简单得到Connection对象的工具类
package com.yds; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.apache.commons.dbutils.DbUtils; /** * 得到connection对象 * @author yu * */ public class GetConnection { private static GetConnection connection; private GetConnection(){ } public static GetConnection getInstants(){ if(connection==null){ connection=new GetConnection(); } return connection; } /** * 得到connection对象 * @return */ public Connection getConn(){ Connection conn=null; boolean flag=DbUtils.loadDriver("com.mysql.jdbc.Driver"); if(flag){ try { conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "1234"); } catch (SQLException e) { } } return conn; } }
实现DBUtils查询所有
package com.yds; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.MapListHandler; /** * 查询所有 * @author yu * */ public class QueryAll { public static void main(String[] args) { GetConnection getConnection=GetConnection.getInstants(); Connection conn=getConnection.getConn(); //创建查询器 QueryRunner query=new QueryRunner(); try { List list=(List)query.query(conn,"select * from t_user", new MapListHandler()); for(Object obj:list){ Map map=(Map)obj; System.out.println(map.get("id")); } } catch (SQLException e) { e.printStackTrace(); }finally { try { DbUtils.close(conn); } catch (SQLException e) { e.printStackTrace(); } } } }
增加
package com.yds; import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.ScalarHandler; /** * 增删改操作 * insert和update的区别 * insert插入进去的值,返回插入的主键id * update执行后,返回影响后的条数 * @author yu * */ public class Cud { public static void main(String[] args) { GetConnection getConnection=GetConnection.getInstants(); Connection conn=getConnection.getConn(); create(conn); } public static void create(Connection conn){ QueryRunner qr=new QueryRunner(); StringBuffer sql=new StringBuffer(); sql.append("insert into t_user(userName,passWord) values("); sql.append("‘测试用户名‘"); sql.append(","); sql.append("‘测试密码‘"); sql.append(")"); try { //qr.update(conn, sql.toString(), null); Long pk=qr.insert(conn, sql.toString(),new ScalarHandler<Long>()); System.out.println(pk); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
返回对象封装、代码和jar在附件中。
本文出自 “code穿梭” 博客,请务必保留此出处http://ityds.blog.51cto.com/1831752/1795967
标签:dbutils
原文地址:http://ityds.blog.51cto.com/1831752/1795967