模拟QueryRunner

本文介绍了一个基于C3P0连接池的数据库操作类模拟QueryRunner的实现细节,包括增删改查等基本操作,并通过具体示例展示了如何使用该类执行SQL语句。
package dbutils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class 模拟QueryRunner<T> {
    //线程池对象
    private DataSource dataSource;

    //默认使用c3p0-config.xml配置的连接池
    public 模拟QueryRunner() {
        dataSource = new ComboPooledDataSource();
    }

    //使用用户传入的连接池
    public 模拟QueryRunner(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    //执行对数据库的增删改操作
    public int update(String sql, Object... params) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            //使用C3P0连接池得到数据库连接对象
            con = dataSource.getConnection();
            //根据动态sql语句创建PreparedStatement对象
            pstmt = con.prepareStatement(sql);
            //为PreparedStatement绑定的sql语句设置参数
            initParams(pstmt, params);
            //执行sql命令并返回影响行数
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //为PreparedStatement绑定的sql语句设置参数
    private void initParams(PreparedStatement pstmt, Object... params) throws SQLException {
        for (int i = 0; i < params.length; i++) {
            pstmt.setObject(i + 1, params[i]);
        }
    }

    //执行对数据库的单行结果查询操作
    public T query(String sql, RsHandler<T> rh, Object... params) {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            //使用C3P0连接池得到数据库连接对象
            con = dataSource.getConnection();
            //根据动态sql语句创建PreparedStatement对象
            pstmt = con.prepareStatement(sql);
            //为PreparedStatement绑定的sql语句设置参数
            initParams(pstmt, params);
            //执行sql命令并返回影响行数
            rs = pstmt.executeQuery();
            //使用handler()方法将结果集创建为指定对象并返回
            return rh.handler(rs);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (pstmt != null) {
                    pstmt.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}


模拟QueryRunnerTest.java

package dbutils;

import org.junit.jupiter.api.Test;

import java.sql.ResultSet;
import java.sql.SQLException;

//传入ResultSet对象返回指定对象
interface RsHandler<T> {
    T handler(ResultSet rs) throws SQLException;
}

public class 模拟QueryRunnerTest {
    //增删改测试
    @Test
    public void testUpdate() {
        Object[] params = {10002, "董小天二号"};
        new 模拟QueryRunner<Student>().update("INSERT INTO table2 VALUES(?, ?)", params);
    }

    //查询测试
    @Test
    public void testQuery() {
        //创建实现RsHandler接口的Student类型实现类
        RsHandler<Student> rh = new RsHandler<Student>() {
            @Override
            public Student handler(ResultSet rs) throws SQLException {
                if (rs == null) {
                    return null;
                }
                Student stu = new Student();
                rs.next();//!!!!!!!将结果集光标从beforeFirst 移动至 first 结果集首行
                stu.setId(rs.getInt(1));
                stu.setName(rs.getString(2));
                return stu;
            }
        };

        模拟QueryRunner<Student> qr = new 模拟QueryRunner();
        Student stu = qr.query("SELECT * FROM table2 WHERE id = ?", rh, 10002);
        System.out.println(stu);
    }
}

package com.sasda; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Scanner; public class MilepostService { // 模拟插入里程碑信息的方法 public Milepost insertMilepostInfo() throws ParseException { Milepost milepost = new Milepost(); Scanner sc = new Scanner(System.in); System.out.println("请输入里程碑信息:"); System.out.print("里程碑名称: "); milepost.setName(sc.next()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); System.out.print("发射时间(格式:2025-06-24): "); milepost.setLaunchtime(formatter.parse(sc.next())); System.out.print("里程碑描述: "); milepost.setDepict(sc.next()); System.out.print("里程碑状态(数字表示): "); milepost.setState(sc.nextInt()); return milepost; } public void addMilepost(Milepost milepost) throws Exception { //创建QueryRunner对象 QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource()); //定义插入里程碑SQL String sql = "insert into milepost(name, launchtime, depict, state)" + " values(?, ?, ?, ?)"; //设置传入SQL中的参数值 Object[] params = {milepost.getName(), milepost.getLaunchtime(), milepost.getDepict(), milepost.getState()}; //执行插入里程碑信息的SQL int count = qr.update(sql, params); //输出插入结果判断是否成功 if (count < 1) { System.out.println("新增里程碑添加失败!"); } else { System.out.println("新增里程碑添加成功!"); } } // 根据ID查询里程碑信息 public Milepost getMilepostById(int id) throws Exception { QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource()); String sql = "SELECT * FROM milepost where id =?"; return qr.query(sql, new BeanHandler<>(Milepost.class), id); } //删除里程碑信息 public void deleteMilepost(int mid) throws Exception { QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource()); String sql = "delete from milepost where id = ?"; int count = qr.update(sql, mid); if (count < 1) { System.out.println("删除里程碑失败!"); } else { System.out.println("删除里程碑成功!"); } } // 修改里程碑信息 public void updateMilepost(Milepost milepost ) throws Exception { QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource()); String sql = "update milepost set name = ?, launchtime = ?, depict = ?, state = ? where id = ?"; Object[] params = { milepost.getName(), milepost.getLaunchtime(), milepost.getDepict(), milepost.getState(), milepost.getId() }; int count = qr.update(sql, params); if (count < 1) { System.out.println("修改里程碑失败!"); } else { System.out.println("修改里程碑成功!"); } } // 可选:用于测试 main 方法 public static void main(String[] args) throws ParseException { MilepostService service = new MilepostService(); Milepost milepost = service.insertMilepostInfo(); System.out.println("您输入的里程碑信息如下:"); System.out.println(milepost); } }
07-04
内容概要:本文介绍了一个基于冠豪猪优化算法(CPO)的无人机三维路径规划项目,利用Python实现了在复杂三维环境中为无人机规划安全、高效、低能耗飞行路径的完整解决方案。项目涵盖空间环境建模、无人机动力学约束、路径编码、多目标代价函数设计以及CPO算法的核心实现。通过体素网格建模、动态障碍物处理、路径平滑技术和多约束融合机制,系统能够在高维、密集障碍环境下快速搜索出满足飞行可行性、安全性与能效最优的路径,并支持在线重规划以适应动态环境变化。文中还提供了关键模块的代码示例,包括环境建模、路径评估和CPO优化流程。; 适合人群:具备一定Python编程基础和优化算法基础知识,从事无人机、智能机器人、路径规划或智能优化算法研究的相关科研人员与工程技术人员,尤其适合研究生及有一定工作经验的研发工程师。; 使用场景及目标:①应用于复杂三维环境下的无人机自主导航与避障;②研究智能优化算法(如CPO)在路径规划中的实际部署与性能优化;③实现多目标(路径最短、能耗最低、安全性最高)耦合条件下的工程化路径求解;④构建可扩展的智能无人系统决策框架。; 阅读建议:建议结合文中模型架构与代码示例进行实践运行,重点关注目标函数设计、CPO算法改进策略与约束处理机制,宜在仿真环境中测试不同场景以深入理解算法行为与系统鲁棒性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值