配置文件、xml、数据库连接池druid
数据驱动获取Connection 需要传入数据地址、用户、密码这些东西最好别写死在程序里面 所以配置文件来了,xml来了。
配置文件
非Java项目 创建配置文件在src下面 会自动编译到classes下面的
如果是web项目就创建在resource下面 会自动编译到classes下面的
build一下run 一下 就会在classes下面生成 相同文件
这是非web项目
web项目
读取配置文件 Properties
因为配置文件会编译到classes下面 所以可以用IO流 获取
InputStream stream = Main.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(stream);
Set<String> strings = properties.stringPropertyNames();
for (String string : strings) {
System.out.println(properties.getProperty(string));
}
XML
数据库连接池
数据库连接池可以提高访问数据库的新年,负责创建、分配、管理和释放数据库连接。
基本思想:自己百度吧 😄
存放方式和配置文件一样
API
似乎是dataSource 和Connect无需你关闭 druid会自动管理
InputStream stream = Main.class.getClassLoader().getResourceAsStream("druid.properties");
Properties properties = new Properties();
properties.load(stream);
Set<String> strings = properties.stringPropertyNames();
for (String string : strings) {
System.out.println(properties.getProperty(string));
}
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("select username,id,password from user;");
ResultSet set = statement.executeQuery();
while (set.next()) {
System.out.println(set.getInt("id") + " " + set.getString("username") + " " + set.getString("password"));
}