硬链接,不由外部配置,由代码创建默认对象并手动设定参数
软链接,由外部配置,内部工厂根据配置创建对应的数据库连接池对象
package com.aistart.tech.pool;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DruidDemo {
public static void main(String[] args) throws Exception {
//注册驱动
//用德鲁伊替换掉
DruidDataSource druidDataSource = new DruidDataSource();
Properties info = new Properties();
info.load(DruidDemo.class.getClassLoader().getResourceAsStream("com/aistart/tech/config/druid.properties"));
/*硬链接,不由外部配置,由代码创建默认对象并手动设定参数*/
// //必须参值
// druidDataSource.setUrl(info.getProperty("url"));
// druidDataSource.setUsername(info.getProperty("username"));
// druidDataSource.setPassword("root");
// //选项参值
// druidDataSource.setInitialSize(5);
// druidDataSource.setMaxActive(10);
/*软链接,由外部配置,内部工厂根据配置创建对应的数据库连接池对象*/
DataSource dataSource = DruidDataSourceFactory.createDataSource(info);
//获取连接
Connection connection = null;
try {
connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select * from user where user_id = 1001");
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
System.out.println("有结果");
}else {
System.out.println("没结果");
}
//获取操作对象
//
//
} catch (SQLException e) {
throw new RuntimeException(e);
}
//用数据库连接池回收连接
connection.close();
}
}