jdbc中从properties文件中读取数据库连接字符串

    技术2022-06-26  47

    --------------------------------1-------------------------

    package com;

    import java.io.InputStream;import java.util.Properties;

    import com.sun.org.apache.xml.internal.security.keys.content.RetrievalMethod;/* *把配置文件读到内存 以后方便ConnectionManager读取 */public final class Env extends Properties { private static Env instrance;//声明一个储存类的变量public static Env getInstance() { if(instrance!=null) {  return instrance;//不为空时直接通过变量获取类的对象 } else {  makeInstrance();//调用实例化方法 return instrance; }}

    private static  void makeInstrance(){ if(instrance==null) {  instrance=new Env();//调用构造方法读取 }}

    private  Env()//构造方法{//把配置文件读取放到内存中现在是在src下的路径 InputStream is=getClass().getResourceAsStream("/connection.properties"); try {  load(is);//加载到内存当中,方便读取 } catch (Exception e) {  System.err.println("错误:没有读取配置文件,请确定connection.properties文件是否存在"); }}}--------------2-----------------------

    package com;

    import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;

    public class ProReader {/* * 读取内存里的信息获取连接 */public static synchronized  Connection getConnection() {     //Env 静态类.方法()则返回一个实例,  //调用Properties类的getProperty()获取hashtabale的value值   String driverClassName=Env.getInstance().getProperty("DRIVER");//驱动   String url=Env.getInstance().getProperty("URL");//数据库url   String password=Env.getInstance().getProperty("PW");//密码   String username=Env.getInstance().getProperty("NAME");//数据库登录名   Connection connection=null;   try {  Class.forName(driverClassName);  connection=DriverManager.getConnection(url,username,password);//写入三个参数 } catch (Exception e) {  e.printStackTrace(); } return connection;}/* * 关闭连接 */public static void closeAll(PreparedStatement pstmt,Connection con,ResultSet rs){

     try {  if (pstmt!=null) {  pstmt.close();  }  if (con!=null) {   con.close();   }  if (rs!=null) {   rs.close();   } } catch (Exception e) {  e.printStackTrace(); } }}


    最新回复(0)