DBUtil java工具类

package com.lideng.util;

import com.lideng.entity.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBUtil {

    /*静态加载*/
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回连接对象
     * @return Connection对象
     */
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEnconding=UTF-8", "root", "root");
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *
     * @param sql 执行的sql语句
     * @param args 参数
     * @return true代表执行成功  反之亦然
     */
    public static boolean executeUpdate(String sql,Object... args){
        PreparedStatement ps =null;
        try {
             ps = getConnection().prepareStatement(sql);

            for (int i=0;i<args.length;i++){
                ps.setObject(i+1, args[i]);
            }


            int i = ps.executeUpdate();
            return  i>0;
        } catch (SQLException e) {
            e.printStackTrace();
            return  false;
        }finally {
            colse(ps);
        }

    }

    /**
     *
     * @param sql
     * @return 查询到的结果集
     */
    public static  List<User> query(String sql){
        List<User> list=new ArrayList<>();
        try {
            PreparedStatement ps = getConnection().prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                User u=new User(rs.getInt(1), rs.getString(2), rs.getString(3));
                list.add(u);
            }

            return  list;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 关闭连接
     * @param autoCloseables
     */
    public static void colse(AutoCloseable... autoCloseables){
        for (AutoCloseable a:autoCloseables){
            if (a!=null){
                try {
                    a.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

  

猜你喜欢

转载自www.cnblogs.com/qurui1997/p/10690821.html
今日推荐