JDBC操作数据库 封装好的工具类

mysql sqlserver  oracle 数据库的驱动jar包
http://download.csdn.net/download/csdn576038874/8833683
package
cn.hp.svse.jdbc; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * 使用本类的方法,必须提供c3p0-copnfig.xml文件 * @author qdmmy6 */ public class JdbcUtils { // 饿汉式 private static DataSource ds = new ComboPooledDataSource(); /** * 它为null表示没有事务 * 它不为null表示有事务 * 当开启事务时,需要给它赋值 * 当结束事务时,需要给它赋值为null * 并且在开启事务时,让dao的多个方法共享这个Connection */ private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); public static DataSource getDataSource() { return ds; } /** * dao使用本方法来获取连接 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { /* * 如果有事务,返回当前事务的con * 如果没有事务,通过连接池返回新的con */ Connection con = tl.get();//获取当前线程的事务连接 if(con != null) return con; return ds.getConnection(); } /** * 开启事务 * @throws SQLException */ public static void beginTransaction() throws SQLException { Connection con = tl.get();//获取当前线程的事务连接 if(con != null) throw new SQLException("已经开启了事务,不能重复开启!"); con = ds.getConnection();//给con赋值,表示开启了事务 con.setAutoCommit(false);//设置为手动提交 tl.set(con);//把当前事务连接放到tl中 } /** * 提交事务 * @throws SQLException */ public static void commitTransaction() throws SQLException { Connection con = tl.get();//获取当前线程的事务连接 if(con == null) throw new SQLException("没有事务不能提交!"); con.commit();//提交事务 con.close();//关闭连接 con = null;//表示事务结束! tl.remove(); } /** * 回滚事务 * @throws SQLException */ public static void rollbackTransaction() throws SQLException { Connection con = tl.get();//获取当前线程的事务连接 if(con == null) throw new SQLException("没有事务不能回滚!"); con.rollback(); con.close(); con = null; tl.remove(); } /** * 释放Connection * @param con * @throws SQLException */ public static void releaseConnection(Connection connection) throws SQLException { Connection con = tl.get();//获取当前线程的事务连接 if(connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭! if(connection != null &&!connection.isClosed()) {//如果参数连接没有关闭,关闭之! connection.close(); } } } }
package cn.hp.svse.jdbc;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

public class TxQueryRunner extends QueryRunner {

    //批量操作
    @Override
    public int[] batch(String sql, Object[][] params) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        int[] result = super.batch(con, sql, params);
        JdbcUtils.releaseConnection(con);
        return result;
    }
    //带多个参数的查询
    @Override
    public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)
            throws SQLException {
        Connection con = JdbcUtils.getConnection();
        T result = super.query(con, sql, rsh, params);
        JdbcUtils.releaseConnection(con);
        return result;
    }
    //不带参数的查询
    @Override
    public <T> T query(String sql, ResultSetHandler<T> rsh) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        T result = super.query(con, sql, rsh);
        JdbcUtils.releaseConnection(con);
        return result;
    }
    //不带参数的增,删,改的操作
    @Override
    public int update(String sql) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        int result = super.update(con, sql);
        JdbcUtils.releaseConnection(con);
        return result;
    }
    //带一个参数的增,删,改的操作
    @Override
    public int update(String sql, Object param) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        int result = super.update(con, sql, param);
        JdbcUtils.releaseConnection(con);
        return result;
    }
    //带多个参数的增,删,改的操作
    @Override
    public int update(String sql, Object... params) throws SQLException {
        Connection con = JdbcUtils.getConnection();
        int result = super.update(con, sql, params);
        JdbcUtils.releaseConnection(con);
        return result;
    }
}
package com.wenjie;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import cn.itcast.jdbc.JdbcUtils;
import cn.itcast.jdbc.TxQueryRunner;

/**
 * dao层要操作数据库
 * 调用测试代码
 * new一个 QueryRunner qr = new TxQueryRunner();
 * 
 * qr.query(),qr.update()...所有的方法都是不需要获取连接的 因为在TxQueryRunner这个类中 每个方法都写了Connection con = JdbcUtils.getConnection();
 * 获取连接所以调用方法时,无需再获取连接
 * @author 00
 *
 */
public class JdbcTest {
    /**
     * 添加
     * 给stuinfo插入一条数据
     * @throws Exception
     */
    @Test
    public void update1() throws Exception{
        QueryRunner qr = new TxQueryRunner();
        //sql语句
        String sql = "insert into stuinfo(stuname,stuno,stuage,stuaddress,stuemail) values(?,?,?,?,?)";
        //参数
        Object[] params = {"aa","123","22","asdasd","asd@qq.com"};
        qr.update(sql, params);
    }
    
    /**
     * 修改
     * 把stuid=10020的学生的名字改为关凤
     * @throws SQLException
     */
    @Test
    public void update2() throws SQLException{
        String sql = "update stuinfo set stuname=? where stuid=?";
        QueryRunner qr = new TxQueryRunner();
        Object[] params = {"关凤","10020"};
        qr.update(sql, params);
    }
    
    /**
     * 删除
     * 将stuid=10021的学生删除掉
     * @throws SQLException
     */
    @Test
    public void update3() throws SQLException{
        String sql = "delete from stuinfo where stuid=?";
        QueryRunner qr = new TxQueryRunner();
        Object[] params = {"10021"};
        qr.update(sql, params);
    }
    
    /**
     * 查询
     * 根据id查询  一个参数的查询 查询出stuid=10000的学生的信息  这里query的第二个参数要为BeanHandler<User>(User.class)
     * 因为查询出来必是一个对象  最后加上参数param
     * @throws SQLException
     */
    @Test
    public void query1() throws SQLException{
        String sql = "select * from stuinfo where stuid=?";
        QueryRunner qr = new TxQueryRunner();
        Object param = 10000;
        User user = qr.query(sql, new BeanHandler<User>(User.class),param);
        System.out.println(user);
    }
    
    /**
     * 查询所有
     * query的第二个参数要为BeanListHandler<User>(User.class)  查询多月没有参数 
     * @throws SQLException
     */
    @Test
    public void query2() throws SQLException{
        String sql = "select * from stuinfo";
        QueryRunner qr = new TxQueryRunner();
        List<User> users = qr.query(sql, new BeanListHandler<User>(User.class));
        for (int i = 0; i < users.size(); i++) {
            System.out.println(users.get(i));
        }
    }
    
    /**
     * 根据id查询  吧查询出来的结果映射成map对象  如果是单表操作的话  MapHandler和BeanHandler没有区别 
     * 但是如果你要操作的表 与其他表有外键关系的话  用BeanHandler那么外键就映射不到为空值
     * 你必须先用MapHandler 然后得到所有的列的数据 然后再转换成实体  这个大家自己试试就知道了
     * @throws SQLException
     */
    @Test
    public void query3() throws SQLException{
        String sql = "select * from stuinfo where stuid=?";
        QueryRunner qr = new TxQueryRunner();
        Object param = 10001;
        Map<String, Object> map = qr.query(sql, new MapHandler(),param);
        System.out.println(map);
    }
    
    @Test
    public void query4() throws SQLException{
        String sql = "select * from stuinfo";
        QueryRunner qr = new TxQueryRunner();
        List<Map<String, Object>> mapList = qr.query(sql, new MapListHandler());
        for (int i = 0; i < mapList.size(); i++) {
            System.out.println(mapList.get(i));
        }
    }
    
    /**
     * 查询记录数 
     * 用ScalarHandler得到一个对象 转换成Number对象 再用number.intValue()返回int类型的值
     * @throws SQLException
     */
    @Test
    public void query5() throws SQLException{
        String sql = "select count(*) from stuinfo";
        QueryRunner qr = new TxQueryRunner();
        Number number = (Number) qr.query(sql, new ScalarHandler());
        int i = number.intValue();
        System.out.println(i);
    }
    
    /**
     * 批量删除
     * @throws SQLException
     */
    @Test
    public void query6() throws SQLException{
        String sql = "delete from stuinfo where stuid=?";
        Object params[][] = {{"10020"},{"10024"},{"10022"},{"10023"}};
        QueryRunner qr = new TxQueryRunner();
        qr.batch(sql, params);
    }
    
    
    /**
     * 事物操作
     * @throws SQLException
     */
    @Test
    public void query7() throws SQLException{
        try {
            //直接调用写好的jdbcUtils帮助类
            JdbcUtils.beginTransaction();//开启事物
            //修改第一个表的一条数据
                //被事物包含的操作 如果有异常 事物就会回滚  量表的数据都没发生改变
            //修改第二条表的数据
            JdbcUtils.commitTransaction();//两条语句都执行成功后 提交事物
        } catch (SQLException e) {
            try {
                JdbcUtils.rollbackTransaction();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        
        
    }
    
}
//数据库连接的配置文件 必须放在src目录下面  而且名字必须为c3p0-config.xml  以下是以mysql为例 oracle  sqlserver都可以 只要提供相应的驱动jar包即可
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <default-config> 
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">123</property>
        
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">2</property>
        <property name="maxPoolSize">10</property>
    </default-config>
</c3p0-config>

 

转载于:https://www.cnblogs.com/wenjie123/p/4643506.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值