封装工具类Utils

db.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf-8
username = root
password = 1234

Utils
package com.zhaoyang.utils;

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 username = 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");
username = properties.getProperty ("username");
password = properties.getProperty ("password");

//1.加载驱动
Class.forName (driver);

} catch (Exception e){
e.printStackTrace ();
}
}

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

//释放连接
public static void release(Connection connection, 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 (connection!=null) {
try {
connection.close ();
} catch (SQLException throwables) {
throwables.printStackTrace ();
}
}
}

}







posted @ 2022-01-18 21:19  朝阳的博客  阅读(69)  评论(0编辑  收藏  举报