zoukankan      html  css  js  c++  java
  • Java使用apache的开源数据处理框架commons-dbutils完成增删改

    主要使用这个开源jar包的QueryRunner类的update方法来完成数据库的增删改操作。

    package demo;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    import org.apache.commons.dbutils.DbUtils;
    import org.apache.commons.dbutils.QueryRunner;
    
    
    
    
    import jdbcutil.JDBCUtilsConfig;
    
    /*
     * 使用QueryRunner类,实现对数据表的
     * insert delete update
     * 调用QueryRunner类的方法update(Connection con,String sql,Object...param)
     * Object...param 可变参数,Object类型,SQL语句会出现?占位符
     * 数据库连接对象,自定义的工具类传递
     */
    public class QueryRunnerDemo {
        private static Connection con=JDBCUtilsConfig.getConnection();
        public static void main(String[] args) throws SQLException {
            //insert();
            //update();
            delete();
        }
    
        /**
         * 定义方法,QueryRunner 类的方法delete将数据表的数据删除
         * 
         */
        public static void delete()throws SQLException{
            //创建QueryRunner对象
            QueryRunner qr=new QueryRunner();
            //写删除的SQL语句
            String sql="delete from sort where sid=?";
            //调用QueryRunner方法update
            int row=qr.update(con,sql,8);
            System.out.println(row);
            DbUtils.closeQuietly(con);
            
        }
        
        
        /**
         * 定义方法,使用QueryRunner类的方法update将数据表的数据修改
         * @throws SQLException 
         * 
         */
        public static void update() throws SQLException{
            QueryRunner qr=new QueryRunner();
            String sql="update sort set sname=?,sprice=?, sdesc=? where sid=?";
            Object[] params={"花卉",100.88,"情人节玫瑰花","4"};
            int row=qr.update(con, sql,params);
            DbUtils.close(con);
            System.out.println(row);
        }
        
        
        
        /**
         * 定义方法,使用QueryRunner类的方法update向数据表中,添加数据
         * @throws SQLException 
         */
        public static void insert() throws SQLException{
            //创建QueryRunner类的对象
            QueryRunner qr=new QueryRunner();
            String sql="insert into sort (sname,sprice,sdesc) values (?,?,?)";
            //将三个?占位符的实际参数,写在数组中
            Object[] params={"体育用品",289.32,"购买体育用品"};
            //调用QueryRunner类的方法update执行SQL语句
            int row=qr.update(JDBCUtilsConfig.getConnection(),sql,params);
            System.out.println(row);
            DbUtils.closeQuietly(con);
        }
    }
  • 相关阅读:
    VIJOS-P1340 拯救ice-cream(广搜+优先级队列)
    uva 11754 Code Feat
    uva11426 GCD Extreme(II)
    uvalive 4119 Always an Interger
    POJ 1442 Black Box 优先队列
    2014上海网络赛 HDU 5053 the Sum of Cube
    uvalive 4795 Paperweight
    uvalive 4589 Asteroids
    uvalive 4973 Ardenia
    DP——数字游戏
  • 原文地址:https://www.cnblogs.com/benjamin77/p/9143715.html
Copyright © 2011-2022 走看看