读取类
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.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=test
jdbc.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;
}