原生jdbc操作db进行crud代码改进

旧版本:

 // 执行查询操作
    public static ResultSet executeQuery(String sql, Object... params) throws SQLException {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }

        // 记录日志
        logger.info("Executing SQL query: {}", sql);

        return preparedStatement.executeQuery();
    }

    // 执行更新操作
    public static int executeUpdate(String sql, Object... params) throws SQLException {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }

        // 记录日志
        logger.info("Executing SQL update: {}", sql);

        return preparedStatement.executeUpdate();
    }

改进后

private static Object execute(String sql, Object... params) throws SQLException {
    Connection connection = getConnection();
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    for (int i = 0; i < params.length; i++) {
        preparedStatement.setObject(i + 1, params[i]);
    }

    // 根据SQL语句中的关键字来确定操作类型
    boolean isSelectQuery = sql.trim().toLowerCase().startsWith("select");

    // 记录日志
    if (isSelectQuery) {
        logger.info("Executing SQL query: {}", sql);
        return preparedStatement.executeQuery();
    } else {
        logger.info("Executing SQL update: {}", sql);
        int rowsAffected = preparedStatement.executeUpdate();
        // 如果需要获取生成的主键等信息,可以在这里添加代码
        return rowsAffected;
    }
}

你可能感兴趣的:(数据库,java,前端)