读取properties实现数据库连接

来源:互联网 发布:2016高速公路数据分析 编辑:程序博客网 时间:2024/05/20 22:02
读取类
public class ReadProperties {//读取配置文件public String readProperties(String filename,String propertiesname) throws IOException{InputStream in=this.getClass().getClassLoader().getResourceAsStream(filename);Properties prop=new Properties();try{prop.load(in);}catch (IOException e) {   e.printStackTrace();  }return prop.getProperty(propertiesname);}}
properties文件
jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/testjdbc.username=testjdbc.password=123456

数据库连接代码

public Connection getConnection()throws Exception{ReadProperties rp=new ReadProperties();String filename="database.properties";String driver=rp.readProperties(filename, "jdbc.driverClassName");String url=rp.readProperties(filename, "jdbc.url");String username=rp.readProperties(filename,"jdbc.username");String password=rp.readProperties(filename,"jdbc.password");Connection conn=null;//加载驱动System.out.println(driver);Class.forName(driver);conn=DriverManager.getConnection(url,username,password);//return conn;}


原创粉丝点击