= true;
} catch (SQLException e) {
log.error("调用存储过程" + sqlStr + "失败!");
e.printStackTrace();
}
return flag;
}
}
Spring数据源的灵活配置巧应用(4)
时间:2011-06-01
四、写测试类
package com.lavasoft.dbtest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by IntelliJ IDEA.
* File: Test.java
* User: leizhimin
* Date: 2008-2-21 14:41:49
* Spring 数据源应用测试
*/
public class Test {
private static final Log log = LogFactory.getLog(Test.class);
public static void main(String args[]) {
Test.test();
}
public static void test() {
String testSql = "select * from t_user";
Connection conn = DBUtil.makeConnection();
Statement stmt = null;
try {
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
ResultSet rs = stmt.executeQuery(testSql);
while (rs.next()) {
String firstName = rs.getString("firstname");
String lastName = rs.getString("lastname");
System.out.println(firstName + " " + lastName);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.info("关闭Statement对象出现异常!");
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.error("关闭数据库连接失败!");
e.printStackTrace();
}
}
}
}
}
测试运行结果:
haha hehe
lei aaa
Process finished with exit code 0
Spring数据源的灵活配置巧应用(5)
时间:2011-06-01
五、数据源置换
Spring实现的DriverManagerDataSource并没有提供连接池的功能,只是用来作简单的单机连接测试,并不适合使用于真正的项目当中,可以考虑用比较成熟的数据连接池来取代。Apache DBCP连接池是不错,如要要替换,则需要加载DBCP相关的工具包。
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!--数据库的数据源定义-->
|