package com.jdbc.test; 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; /** * @author 李逸野 * */ public class DBHelperUtil{ //获取数据库用户名 private static String user; //获取数据库密码 private static String password; //获取数据库驱动 private static String driver; //获取数据库URL private static String jdbcUrl; //加载文件 private static Properties properties; //获取加载文件 private static InputStream getProperties; //单例模式获取数据库实体 private static DBHelperUtil etity; //获取连接对象 private static Connection conn = null; //私有化 private DBHelperUtil(){ } //通过静态代码块加载配置文件 static{ properties = new Properties(); getProperties = DBHelperUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); try { properties.load(getProperties); } catch (IOException e) { e.printStackTrace(); } user = properties.getProperty("user"); password=properties.getProperty("password"); driver=properties.getProperty("driver"); jdbcUrl=properties.getProperty("jdbcUrl"); etity = new DBHelperUtil(); } //单例模式获取数据库连接 public static Connection createInstance() throws IOException, ClassNotFoundException, SQLException{ if(conn == null){ synchronized(Object.class){ if(conn == null){ conn = DriverManager.getConnection(jdbcUrl, user, password); etity.initDB(); } } } return conn; } //初始化连接 public void initDB() throws ClassNotFoundException{ Class.forName(driver); } //关闭数据库连接 public static void close(ResultSet resultSet,PreparedStatement perparedStatement,Connection conn) throws SQLException, IOException{ if(resultSet != null){ resultSet.close(); } if(perparedStatement != null){ perparedStatement.close(); } if(conn != null){ conn.close(); } if(getProperties != null){ getProperties.close(); } } }
测试数据:
结合本人最近学习的单例模式和JDBC写出个简单的获取JDBC连接,如果有错误欢迎指教。