From b8df35d5e2fafc7473d69e52e2e27a30c51550e3 Mon Sep 17 00:00:00 2001 From: nxist2202005014 <1463859337@qq.com> Date: Wed, 26 Jun 2024 09:48:52 +0800 Subject: [PATCH] ADD file via upload --- Jdbc.java | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Jdbc.java diff --git a/Jdbc.java b/Jdbc.java new file mode 100644 index 0000000..d5a4a9a --- /dev/null +++ b/Jdbc.java @@ -0,0 +1,84 @@ +package flowershop.daoimpl; + + +import java.io.IOException; +import java.io.InputStream; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Properties; + +public class Jdbc { + // 数据连接URL + static String url; + // 创建Properties对象 + static Properties info = new Properties(); + + // 静态代码块 + static { + // 获取属性文件的输入流 + InputStream input = Jdbc.class.getClassLoader().getResourceAsStream("config.properties"); + + try { + if (input == null) { + throw new NullPointerException("配置文件未找到"); + } + + // 加载属性文件 + info.load(input); + + // 从属性文件中读取url + url = info.getProperty("url"); + + // 从属性文件中读取driver + String driverClassName = info.getProperty("driver"); + + // 加载驱动程序 + Class.forName(driverClassName); + System.out.println("驱动程序加载成功..."); + + } catch (ClassNotFoundException e) { + System.out.println("驱动程序加载失败..."); + e.printStackTrace(); + } catch (IOException e) { + System.out.println("属性文件加载失败..."); + e.printStackTrace(); + } catch (NullPointerException e) { + System.out.println(e.getMessage()); + } + } + + // 创建数据连接 + public static Connection getConnection() throws SQLException { + // 创建数据连接 + Connection conn = DriverManager.getConnection(url, info); + return conn; + } + + // 关闭连接方法 + public static void close(ResultSet rs, PreparedStatement pstmt, Connection conn) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + if (pstmt != null) { + try { + pstmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } +} \ No newline at end of file