栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

jdbc工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jdbc工具类

定义配置文件放在src目录下

#数据库连接路径
url=jdbc:mysql://localhost/day16
#登录用户名
username=root
#登录密码
password=root
#注册驱动
driver=com.mysql.jdbc.Driver

数据库连接工具类

package cn.itcast.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private static String url;
    private static String users;
    private static String password;
    private static String driver;

    
    static{
        //读取资源文件获取值
        Properties pro = new Properties();
        try {
            //获取src路径下文件的方式-->ClassLoader
            ClassLoader cl = JDBCUtils.class.getClassLoader();
            URL res = cl.getResource("jdbc.properties");
            String path = res.getPath();
            pro.load(new FileInputStream(path));
            url = pro.getProperty("url");
            users = pro.getProperty("users");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");

//            注册驱动
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
    


    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,users,password);
    }


    
    public static void close(Statement stmt,Connection conn){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void close(Statement stmt, Connection conn, ResultSet rs){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(rs !=null ){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/843323.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号