JDBC——封装工具类

package net.cyan.cy01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCutil {
//使用静态代码块进行流的操作
private static String user;
private static String password;
private static String url;
private static String className;
static{//此代码块仅在类加载时运行一次
FileInputStream fis=null;
try {
Properties properties=new Properties();
//创建读取数据的流
fis =new FileInputStream(“jdbc.txt”);
//1.3加载流
properties.load(fis);
user = properties.getProperty(“user”);
password = properties.getProperty(“password”);
url = properties.getProperty(“url”);
className = properties.getProperty(“className”);
} catch (FileNotFoundException e) {
//将编译时异常转化为运行异常
throw new RuntimeException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流操作
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static Connection getConnection() {
//通过反射获取对象
try {
Class.forName(className);
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
} catch (ClassNotFoundException e) {
//将编译时异常转化为运行异常
throw new RuntimeException(e.getMessage());
}

public static void close(PreparedStatement ps, Connection connection) {
if (ps!=null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}

public static void close(PreparedStatement ps, Connection connection, ResultSet resultSet) {
close(ps,connection);
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}

Original: https://www.cnblogs.com/CYan521/p/16469764.html
Author: 再美不及姑娘你
Title: JDBC——封装工具类

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/562322/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球