从properties文件中获取数据进行数据库连接
properties文件位置
$PATH/project_name/src/jdbc.properties
- 在src目录下的properties文件会在WEB-INF/classes下自动生成一个相同的properties文件。
- 如果在下面的代码中运行语句:
System.out.println(classLoader.getResource(propertiesName).getPath());
将会打印:
..../ProjectName/WebContent/WEB-INF/classes/jdbc.properties
而不是
..../ProjectName/src/jdbc.properties
properties文件内容
# [/jdbc.properties]
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/database_name
user=root
password=
读取文件数据
String propertiesName = "jdbc.properties";
ClassLoader classLoader =
JDBCUtils.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(propertiesName);
Properties properties = new Properties();
properties.load(inputStream);
String driverClass = properties.getProperty("driverClass");
System.out.println("driverClass: " + driverClass);
String jdbcUrl = properties.getProperty("jdbcUrl");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
从properties文件中中获取数据+得到数据库连接的完整代码
import java.sql.Connection;
import java.io.InputStream;
import java.util.Properties;
import java.sql.DriverManager;
public class JDBCUtils {
public static Connection getConntection2() throws Exception {
String propertiesName = "jdbc.properties";
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(propertiesName);
Properties properties = new Properties();
properties.load(inputStream);
String driverClass = properties.getProperty("driverClass");
String jdbcUrl = properties.getProperty("jdbcUrl");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
Class.forName(driverClass);
return DriverManager.getConnection(jdbcUrl, user, password);
}
}