欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2021-08-07 jdbc程序前所用到的配置文件和工具库

程序员文章站 2022-04-29 23:53:33
...
package com.kuang.lesson02.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class jdbcUtils {
    private static String driver=null;
    private static String url=null;
    private static String usename=null;
    private static String password=null;
    static {
        try {
            InputStream in = jdbcUtils.class.getClassLoader ().getResourceAsStream ("db.properties");
            Properties properties = new Properties ();
            properties.load (in);
            driver = properties.getProperty ("driver");
            url = properties.getProperty ("url");
            usename = properties.getProperty ("usename");
            password = properties.getProperty ("password");
            Class.forName (driver);
        }
        catch (Exception e) {
            e.printStackTrace ();
        }
    }


        //  获取连接
       public static Connection getConnection() throws SQLException {
            return DriverManager.getConnection (url,usename,password);
        }



        //  释放资源
        public static void release(Connection con, Statement st, ResultSet rs){
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace ();
            }
        }
            if(st!=null) {
                try {
                    st.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace ();
                }
                if(con!=null) {
                    try {
                        con.close();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace ();
                    }
                }

            }
        }
        }


driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=root

图一:jdbcUtils

图二:dp.peoperties