【jsp】mysql 封装类

【jsp】mysql 封装类 大家拿着就能使用

 

 

复制代码
package bean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {

    static {
        //MySQL 5.7及以下使用的代码
        String driverClass="com.mysql.jdbc.Driver";
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }     // 加载数据库驱动
    }
    
    public DBUtil() {
        // TODO Auto-generated constructor stub
    }
    
    
    //获取数据库连接
    public static Connection getConnection() {
        String url="jdbc:mysql://localhost:3307/stu";
        String username = "root";
        String password = "";
        Connection conn = null;
        try {
             conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    
    
    //获取静态语句操作对象
    public static Statement getStatement(Connection conn) {
        Statement stat = null;
        try {
            stat = conn.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stat;
    }
    
    //释放资源
    public static void closeAll(Connection connection, Statement statement,ResultSet resultSet){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
            if (connection!=null){
                connection.close();
 
            }
            if (statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    //释放资源  (方法重载)
    public static void close(Connection connection, Statement statement){
        try {
            if (connection!=null){
                connection.close();
            }
            if (statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

 
}
复制代码

 

posted @   一叶一花  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示