1.新建一个db.properties文件,在src下新建包例如:com.lwz.db 然后把db.properties文件放在该包中。
配置文件的内容如下
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/lwz
username=root
password=111111
他们都是key value对应的
2 在程序中读取文件信息
程序代码如下
public Connection getConnection() {
Properties properties = new Properties();
try {
properties.load(this.getClass().getResourceAsStream("com.lwz.db /db.properties"));
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
try {
Class.forName(driver);
try {
conn = DriverManager.getConnection(url,username, password);
System.out.println("好了啊成果了�");
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
这样就可以读取信息了 避免了把连接信息写在程序中 不利于修改 如果编译之后根本没法修改配置信息