读取类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;
}

本文介绍了一个Java程序如何通过读取properties配置文件来获取数据库连接参数,并使用这些参数建立数据库连接的方法。该程序定义了ReadProperties类用于读取配置文件,以及getConnection方法用于创建数据库连接。
569

被折叠的 条评论
为什么被折叠?



