日期:2014-05-16  浏览次数:20366 次

common-jdbc配置

1.使用Maven构建依赖关系

 <dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>

2.spring配置dataSource bean对象

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/test1</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>wodwl</value>
</property>
</bean>

3.编写测试代码

ApplicationContext ctx = new FileSystemXmlApplicationContext(
"src/main/resources/spring.xml");
Connection conn = null;
Statement stmt = null;
DataSource dataSource=(BasicDataSource)ctx.getBean("dataSource");

try {
conn = dataSource.getConnection();
stmt = conn.createStatement();
stmt.executeUpdate("UPDATE test1 SET name = 'wwww'");
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {

}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {

}
}
}