ubuntu

# ubuntu

## DBUtils 基本介绍

commons-dbutils是Apache组织提供的一个开源JDBC工具类库,它是对JDBC的简单封装。简化了jdbc编码的工作量

## 地址

![image-20201217194115785](ubuntu.assets/image-20201217194115785.png)

## **代码**

update()方法可用于Insert、update、delete

```java

public class JDBCTest06 {

    // 删除delete

    public JDBCTest06() throws SQLException {

        // 1. 创建QueryRunner 的实现类

        QueryRunner queryRunner = new QueryRunner();

        // 2. 使用其update 方法

        String sql = "DELETE FROM customers " + "WHERE id IN(?,>)";

        DataSource dataSource = new ComboPooledDataSource("helloc3p0");

        // 3. 在连接池获取连接

        Connection connection =  dataSource.getConnection();

        queryRunner.update(connection,sql,12,13); // update方法可用于删除、更新、添加

        connection.close();

    }

}

```

通过实现ResultSetHandler接口实现查询

创建 ResultSetHandler接口 的实现类,实现handle方法,queryRunner.query()的返回值取决于handle的返回值

```java

public class DBUtilsTest {

    QueryRunner queryRunner = new QueryRunner();

    // 1. 创建 ResultSetHandler接口 的实现类,实现handle方法,queryRunner.query()的返回值取决于handle的返回值

    class MyResultSetHandler implements ResultSetHandler{

        @Override

        public Object handle(ResultSet rs) throws SQLException {

            List customers = new ArrayList<>();


            while (rs.next()){

                Integer id = rs.getInt(1);

                String name = rs.getString(2);

                String email = rs.getString(3);

                Date birth = rs.getDate(4);

                Customer customer = new Customer(id,name,email,birth);

                customers.add(customer);

            }

            return customers;

        }

    }

    public void testQuery() throws SQLException {

        Connection connection = null;

        String sql = "select id,name,email,birth" + "from customers";

        Object object = queryRunner.query(connection, sql, new MyResultSetHandler());

        System.out.println(object);

        connection.close();

    }

}

```

queryRunner.query()源码分析

```csharp

//1. QueryRunner 类的query()方法

public T query(Connection conn, String sql, ResultSetHandler rsh, Object... params) throws SQLException {

        return this.query(conn, false, sql, rsh, params);// 返回值是调用当前的类query的重载方法

    }

// 2.当前的类query的重载方法

private T query(Connection conn, boolean closeConn, String sql, ResultSetHandler rsh, Object... params)

            throws SQLException {       

        PreparedStatement stmt = null;

        ResultSet rs = null;

        T result = null;

        try {

            stmt = this.prepareStatement(conn, sql);

            this.fillStatement(stmt, params);

            rs = this.wrap(stmt.executeQuery()); // wrap() 返回的是ResultSet

            result = rsh.handle(rs); //  handle()是ResultSetHandler接口定义的方法

        } catch (SQLException e) {

            this.rethrow(e, sql, params);

        } finally {

            try {

                close(rs);

            } finally {

                close(stmt);

                if (closeConn) {

                    close(conn);

                }

            }

        }

        return result;

    }

```

通过BeanHandler类实现查询

把结果集的第一条记录转为创建BeanHandler对象时传入的class参数对应的对象

```java

    public void testBeanHandler() throws SQLException {

        QueryRunner queryRunner = new QueryRunner();

        Connection connection = null;

        String sql = "select id,name,email,birth" + "from customers where id >= ?";

        Object object = queryRunner.query(connection, sql, new BeanHandler(Customer.class),5);

        System.out.println(object);

        connection.close();

    }

```

通过BeanListHandler类实现查询

把结果集转为一个List,该List不为null,但可能为空集合(size()方法返回为0),若SQL语句有查询记录,List中存放创建BeanListHandler转入Class对象对应的对象

```java

    public void testBeanListHandler() throws SQLException {

        QueryRunner queryRunner = new QueryRunner();

        Connection connection = null;

        String sql = "select id,name,email,birth" + "from customers";

        List customers = queryRunner.query(connection,sql,new BeanListHandler(Customer.class));

        Object object = queryRunner.query(connection, sql, new BeanHandler(Customer.class),5);

        System.out.println(object);

        connection.close();

    }

```

通过MapHandler类实现查询

返回SQL对应的第一条记录对应的Map对象,键值对:键SQL查询的列名(不是别名),列的值

```dart

public void testMapHandler() throws SQLException {

        QueryRunner queryRunner = new QueryRunner();

        Connection connection = null;

        String sql = "select id,name,email,birth" + "from customers";

        Map customers = queryRunner.query(connection,sql,new MapHandler());

        Object object = queryRunner.query(connection, sql, new BeanHandler(Customer.class),5);

        System.out.println(object);

        connection.close();

    }

```

通过MapListHandler类实现查询

将结果集转为一个Map的List,Map对应查询的一条记录:键值堆:键SQL查询的列名(不是列的别名),值:列的值,而MapListHandler:返回的多条记录对应的Map的集合

```dart

    public void testMapListHandler() throws SQLException {

        QueryRunner queryRunner = new QueryRunner();

        Connection connection = null;

        String sql = "select id,name,email,birth" + "from customers";

        List> result = queryRunner.query(connection,sql,new MapListHandler());

        Object object = queryRunner.query(connection, sql, new BeanHandler(Customer.class),5);

        System.out.println(object);

        connection.close();

    }

```

ScalarHandler:把结果集转为一个数值(可以是任意基本数据类型和字符串,Date等)返回

```dart

public void ScalarHandler() throws SQLException {

        QueryRunner queryRunner = new QueryRunner();

        Connection connection = null;

        String sql = "select name" + "from customers"; // 如果是两列的情况返回一列

        List> result = queryRunner.query(connection,sql,new MapListHandler());

        Object object = queryRunner.query(connection, sql, new ScalarHandler<>(),5);

        System.out.println(object);

        connection.close();

    }

```

## 做的完善的欣知商城

entity

```Java

package com.xinzhi.entity;

import com.xinzhi.Cart;

/**

* @author 杨智超

* @date 2020/12/17

*/

public class User {

    private int id;

    //用户名

    private String userName;

    //密码

    private String passWord;

    //地址

    private String site;

    //余额

    private double balance;

    private Cart cart = new Cart();

    public String getUserName() {

        return userName;

    }

    public void setUserName(String userName) {

        this.userName = userName;

    }

    public String getPassWord() {

        return passWord;

    }

    public void setPassWord(String passWord) {

        this.passWord = passWord;

    }

    public String getSite() {

        return site;

    }

    public void setSite(String site) {

        this.site = site;

    }

    public double getBalance() {

        return balance;

    }

    public void setBalance(double balance) {

        this.balance = balance;

    }

    public Cart getCart() {

        return cart;

    }

    public void setCart(Cart cart) {

        this.cart = cart;

    }

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    @Override

    public String toString() {

        return "User{" +

                "id=" + id +

                ", userName='" + userName + '\'' +

                ", passWord='" + passWord + '\'' +

                ", site='" + site + '\'' +

                ", balance=" + balance +

                ", cart=" + cart +

                '}';

    }

}

```

service

```Java

package com.xinzhi.service;

import com.xinzhi.Order;

import com.xinzhi.dao.impl.FileUserDaoImpl;

import com.xinzhi.dao.impl.MysqlUserDaoImpl;

import com.xinzhi.entity.User;

import com.xinzhi.dao.UserDao;

import com.xinzhi.util.ScannerUtil;

import java.util.List;

/**

* @author 杨智超

* @date 2020/12/17

*/

public class UserService {

    UserDao userDao = new MysqlUserDaoImpl();

    public boolean longin(User user2){

        System.out.print("请输入用户名:");

        String userName = ScannerUtil.getInput();

        System.out.println();

        System.out.print("请输入密码:");

        String passWord = ScannerUtil.getInput();

        User user = userDao.getUsersByName(userName);

        if (!userName.equals(user.getUserName())){

            System.out.println("用户不存在,登录失败");

            return true;

        }

        if (!passWord.equals(user.getPassWord())){

            System.out.println("密码不对,登录失败");

            return false;

        }

        user2.setUserName(userName);

        user2.setPassWord(passWord);

        System.out.println("登录成功欢迎" + user2.getUserName() +"用户的到来,祝您有个好的购物心情!");

        return true;

    }

    public boolean regist(){

        System.out.print("请输入用户名:");

        String userName = ScannerUtil.getInput();

        System.out.println();

        System.out.print("请输入密码:");

        String passWord = ScannerUtil.getInput();

        System.out.println();

        System.out.println("请输入您的收货地址:");

        String site = ScannerUtil.getInput();

        User user = new User();

        //创建用户

        user.setUserName(userName);

        user.setPassWord(passWord);

        user.setSite(site);

        user.setBalance(0);

        userDao.saveUser(user,true);

        System.out.println("注册成功");

        return true;

    }

    //查看购物车

    public void lookAtCart(User user){

        List cartMessage = user.getCart().getCartMessage();

        System.out.println("以下为购物车:");

        for (int i = 0; i < cartMessage.size(); i++) {

            System.out.println((i+1) + ":" +

                    cartMessage.get(i).getGoodsName() + "\t" +

                    cartMessage.get(i).getGoodsPrice() + "\t" +

                    cartMessage.get(i).getGoodsCount() + "\t" +

                    cartMessage.get(i).getTotalMoney() + "\t"

            );

        }

        System.out.println("--------------------------------\n");

    }

    //结账

    public void pay(User user2) {

        List cartMessage = user2.getCart().getCartMessage();

        double cartTotalMoney = 0;

        for (Order order : cartMessage) {

            cartTotalMoney += order.getTotalMoney();

        }

        User user = userDao.getUsersByName(user2.getUserName());

        if (user.getBalance() >= cartTotalMoney){

            double balance = user.getBalance() - cartTotalMoney;

            userDao.updateBalance(user2.getUserName(),balance);

            user.getCart().clear();

            System.out.println("支付成功");

            System.out.println("本次支付:" + cartTotalMoney + ",您的余额剩余:" + balance + "元");

        }else {

            System.out.println("余额不足,请在充值");

        }

    }

    //查看用户信息

    public void userManger(User user2){

        User user = userDao.getUsersByName(user2.getUserName());

        System.out.println("用户名:" + user.getUserName());

        System.out.println("剩余金额:" + user.getBalance());

    }

    //充值

    public void showUserManger(User user2){

        User user = userDao.getUsersByName(user2.getUserName());

        System.out.println("当前余额:" + user.getBalance() + "元");

        System.out.println("请输入要充值的金额");

        String input = ScannerUtil.getInput();

        double newBalance = user.getBalance() + Double.parseDouble(input);

        userDao.updateBalance(user.getUserName(),newBalance);

        System.out.println("剩余金额:" + newBalance + "元。");

    }

    public boolean addGoodsToCart(String id, int goodCount,User user){

        user.getCart().addGoods(id, goodCount);

        return true;

    }

}

```

dao

![image-20201217194319164](ubuntu.assets/image-20201217194319164.png)

UserDao接口

```Java

package com.xinzhi.dao;

import com.xinzhi.Constant;

import com.xinzhi.entity.User;

import java.io.*;

import java.util.ArrayList;

import java.util.List;

/**

* @author 杨智超

* @date 2020/12/17

*/

public interface UserDao {

    /**

    * 获取所有USER

    * @param url

    * @return

    */

    List getAllUsers(String url);

    /**

    * 修改价格

    * @param name

    * @return

    */

    User getUsersByName(String name);

    /**

    *  修改余额

    * @param userName

    * @param newBalance

    */

    void updateBalance(String userName,double newBalance);

    /**

    *  保存数据

    * @param user

    * @param append

    * @return

    */

    boolean saveUser(User user,boolean append);

}

```

FileUserDaoImpl

```Java

package com.xinzhi.dao.impl;

import com.xinzhi.Constant;

import com.xinzhi.dao.UserDao;

import com.xinzhi.entity.User;

import java.io.*;

import java.util.ArrayList;

import java.util.List;

/**

* @author 杨智超

* @date 2020/12/17

*/

public class FileUserDaoImpl implements UserDao {

    @Override

    public List getAllUsers(String url){

        List users = new ArrayList<>();

        try (FileReader fs = new FileReader(url);

            BufferedReader bf = new BufferedReader(fs)){

            String userStr = null;

            while ((userStr = bf.readLine()) != null) {

                String[] str = userStr.split("---");

                User user = new User();

                user.setUserName(str[0]);

                user.setPassWord(str[1]);

                users.add(user);

            }

        }catch (IOException ex){

            ex.printStackTrace();

        }

        return users;

    }

    @Override

    public User getUsersByName(String name) {

        List users = getAllUsers(Constant.BASE_PATH);

        for (User user : users) {

            if (user.getUserName().equals(name)) {

                return user;

            }

        }

        return null;

    }

    @Override

    //修改余额

    public void updateBalance(String userName,double newBalance){

        List allUsers = getAllUsers(Constant.BASE_PATH);

        if (userName == null){

            return;

        }

        for (int i = 0; i < allUsers.size(); i++) {

            if (userName.equals(allUsers.get(i).getUserName())){

                allUsers.get(i).setBalance(newBalance);

            }

            if (i == 0){

                saveUser(allUsers.get(i),false);

            }else {

                saveUser(allUsers.get(i),true);

            }

        }

    }

    @Override

    //保存数据

    public boolean saveUser(User user,boolean append){

        FileWriter fw = null;

        BufferedWriter bw = null;

        try {

            fw = new FileWriter(Constant.BASE_PATH,true);

            bw = new BufferedWriter(fw);

            bw.append(user.getUserName()).append("---").append(user.getPassWord()).append("---").append(user.getSite());

            bw.newLine();

            bw.flush();

        }catch (IOException ex){

            ex.printStackTrace();

        }finally {

            try {

                if (bw != null) {

                    bw.close();

                }

                if (fw != null) {

                    fw.close();

                }

            }catch (IOException ex){

                ex.printStackTrace();

            }

        }

        return true;

    }

}

```

MysqlUserDaoImpl

```Java

package com.xinzhi.dao.impl;

import com.xinzhi.dao.UserDao;

import com.xinzhi.entity.User;

import com.xinzhi.util.PollUtil;

import org.apache.commons.dbutils.QueryRunner;

import org.apache.commons.dbutils.ResultSetHandler;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

/**

* @author 杨智超

* @date 2020/12/17

*/

public class MysqlUserDaoImpl implements UserDao {

    ResultSetHandler userHandler = new ResultSetHandler() {

        @Override

        public User handle(ResultSet resultSet) throws SQLException {

            User user = new User();

            resultSet.next();

            user.setId(resultSet.getInt("id"));

            user.setUserName(resultSet.getString("name"));

            user.setPassWord(resultSet.getString("password"));

            user.setSite(resultSet.getString("site"));

            return null;

        }

    };

    ResultSetHandler> userListHandler = new ResultSetHandler>() {

        @Override

        public List handle(ResultSet resultSet) throws SQLException {

            List users = new ArrayList<>();

            while (resultSet.next()) {

                User user = new User();

                user.setId(resultSet.getInt("id"));

                user.setUserName(resultSet.getString("name"));

                user.setPassWord(resultSet.getString("password"));

                user.setSite(resultSet.getString("site"));

                users.add(user);

            }

            return users;

        }

    };

    @Override

    public List getAllUsers(String url) {

        QueryRunner runner = new QueryRunner(PollUtil.getDataSource());

        List users = null;

        try {

            users = runner.query("select * from comsumer",userListHandler);

        } catch (SQLException throwables) {

            throwables.printStackTrace();

        }

        return users;

    }

    @Override

    public User getUsersByName(String name) {

        QueryRunner runner = new QueryRunner(PollUtil.getDataSource());

        User user = null;

        try {

            user = (User) runner.query("select * from comsumer where name=?",userListHandler,name);

        } catch (SQLException throwables) {

            throwables.printStackTrace();

        }

        return user;

    }

    @Override

    public void updateBalance(String userName, double newBalance) {

        QueryRunner runner = new QueryRunner(PollUtil.getDataSource());

        try {

            runner.update("update consumer set site=? where name=?",newBalance,userName);

        } catch (SQLException throwables) {

            throwables.printStackTrace();

        }

    }

    @Override

    public boolean saveUser(User user, boolean append) {

        QueryRunner runner = new QueryRunner(PollUtil.getDataSource());

        int rowd = 0;

        try {

          rowd = runner.update("insert into consumer (name,password,site) values(?,?,?)",user.getId(),user.getUserName(),user.getPassWord(),user.getSite());

        } catch (SQLException throwables) {

            throwables.printStackTrace();

        }

        return rowd > 0;

    }

}

```

你可能感兴趣的:(ubuntu)