参数文档配置的方法,使用Properties 类跟DataSource 类
Properties 类的使用方法:
在根目录底下建以.properties 或者.xml结尾的文件
配置参数
#driver=oracle.jdbc.driver.OracleDriver
#jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#password=java
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/qh_db
user=root
password=123456
在使用的类上声明
Properties properties= new Properties();
InputStream inputStream=TicketDAOImpl.class.getClassLoader.getResourceAsStream("db.properties");
try{
properties.load(inputStream);
}
要使用的时候
user=properties.getProperty("user");
password=properties.getProperty("password");
driverClass=properties.getProperty("driverClass");
jdbcUrl=properties.getProperty("jdbcUrl");
DataRource的用法:
在根目录底下建立c3p0-config.xml文件
配置参数
<c3p0-config>
<named-config name="antBank">
<property name="user">root</property>
<property name="password">123456</property>
<property name="jdbcUrl">jdbc:mysql:///qh_db</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="acquireIncrement">2</property>
<property name="initialPoolSize">5</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">10</property>
<property name="maxStatements">20</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
定义一个私有的静态DataResource变量
private Static DataResource dataSource=null;
static{
dataSource=new ComboPooledDataSource("antBank");
}
需要用的时候
Connection conn=dataSource.getConnection();
使用ThreadLocal(线程局部变量)绑定Cnnection
新建一个类
在类里面定义一个ThreadLocal的私有变量
private ThreadLocal<Connection> connectionThreadLocal=new ThreadLocal<>();
定义connectionThreadLocal的bind方法
public void bind(Connection connection)
{
connectionThreadLocal.set(connection);
}
定义get()方法
public Connection get()
{
return connectionThreadLocal.get();
}
定义remove()方法
public void remove()
{
connectionThreadLocal.remove();
}