0
点赞
收藏
分享

微信扫一扫

UtIL DBUtil

心如止水_c736 2022-03-11 阅读 36

文章目录

class DBUtil

package utils;

import java.sql.*;

/**
 * JDBC工具类,简化JDBC编程。
 */
public class DBUtil {
    /**
     * 工具类中的构造方法都是私有的。
     * 因为工具类中的方法都是静态的,不需要new对象,直接使用类名调用就可以
     */
    private DBUtil() {
        //设置为私用防止new对象
        //为什么不让new因为用不到
    }
    static {
        //静态代码块在类加载时执行并且只执行一次
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取数据库连接对象
     * @return 连接对象
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/sys", "root", "123456");
    }

    /**
     * 关闭连接
     * @param connection 连接对象
     * @param statement 数据库操作对象
     * @param resultSet 结果集
     */
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

class JDBCtest01

import utils.DBUtil;

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

/**
 * 测试工具类
 * 练习模糊查询
 */
public class JDBCtest01 {
    public static void main(String[] args) {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet =null;
        try {
            //获取连接
            connection= DBUtil.getConnection();
            //获取预编译的数据库操作对象
            String sql="select * from t_act where no like ?";
            preparedStatement = connection.prepareStatement(sql);
//            preparedStatement.setString(1,"%1%");
            preparedStatement.setString(1,"_2%");
            resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){
                int no = resultSet.getInt("no");
                double balance = resultSet.getDouble("balance");
                System.out.println(no+"\t"+balance+"\t");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //释放资源
            DBUtil.close(connection,preparedStatement,resultSet);
        }
    }
}

你的点赞和关注,是我继续坚持下去的动力,如果可以请一键三连,谢谢!

个人知识水平有限,如果博客中有误,望指正。

如果欲交流学习,请私信我,我一定会在看到消息时及时回复你。

举报

相关推荐

0 条评论