jdbc.propertie
url=jdbc:mysql:///empye user=root password=root driver=com.mysql.jdbc.Driver
读取资源文件 获取值 创建Properties 集合类
读取jdbc.propertie文件来获得mysql 地址 账号 密码
使用静态的方法
static{ try { // 读取资源文件 获取值 创建Properties 集合类 Properties pro = new Properties(); // 获取src的路径----》ClassLoader() 类加载器 ClassLoader classLoader = JdbcUtils.class.getClassLoader(); URL res = classLoader.getResource("jdbc.properties"); String path = res.getPath(); pro.load(new FileReader(path)); url=pro.getProperty("url"); user=pro.getProperty("user"); password=pro.getProperty("password"); driver=pro.getProperty("driver"); } catch (IOException e) { e.printStackTrace(); } }
//获取链接对象
public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user,password); }
释放两个值的资源
public static void close(Statement stmt,Connection conn){ if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
释放三个值的资源
public static void close(ResultSet rs,Statement stmt, Connection conn){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
Jdbc工具类中的全部代码
package JdbcUtils; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties; /** * JDBC工具类 * */ public class JdbcUtils { private static String url; private static String user; private static String password; private static String driver; // 文件的读取 读取一次拿到所有值 使用静态代码块 static{ try { // 读取资源文件 获取值 创建Properties 集合类 Properties pro = new Properties(); // 获取src的路径----》ClassLoader() 类加载器 ClassLoader classLoader = JdbcUtils.class.getClassLoader(); URL res = classLoader.getResource("jdbc.properties"); String path = res.getPath(); pro.load(new FileReader(path)); url=pro.getProperty("url"); user=pro.getProperty("user"); password=pro.getProperty("password"); driver=pro.getProperty("driver"); } catch (IOException e) { e.printStackTrace(); } } //获取链接对象 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user,password); } //释放资源 public static void close(Statement stmt,Connection conn){ if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } //释放资源 public static void close(ResultSet rs,Statement stmt, Connection conn){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }