1.数据准备
drop table if exists account;
create table if not exists account
(
id int primary key auto_increment,
name varchar(10),
money double(10, 2)
);
insert into account(name, money)
values ('张三', 1000),
('李四', 1000);
2.pom.xml
文件中引用druid
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
3. 在resource目录下创建druid.properties
配置文件
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///db1?useServerPrepStmts=true
username=root
password=root1234
# 初始化连接数量
initialSize=5
# 最大连接数量
maxActive=10
# 最大等待时间
maxWait=3000
4. 编写java代码
Properties prop = new Properties();
prop.load(Main.class.getClassLoader().getResourceAsStream("druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
Connection connection = dataSource.getConnection();
String sql = "select * from account";
PreparedStatement prepareStatement = connection.prepareStatement(sql);
ResultSet resultSet = prepareStatement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double money = resultSet.getDouble("money");
System.out.println("id = " + id + " , name = " + name + " , money = " + money);
}
resultSet.close();
prepareStatement.close();
connection.close();
参考文献
1. 黑马程序员JavaWeb基础教程