这个page on Spring JDBC


DataSourceUtils类…提供静态方法以从JNDI获取连接


但是据我所知,the API doc for DataSourceUtils不包括上述静态方法。

我想念什么?

最佳答案

嗯...以某种方式,DataSourceUtils的Javadoc更“准确”(我的意思是,该文档没有错,但是从技术上讲,您从DataSource获得了连接-可以通过JNDI获得):


帮助程序类,提供了用于从DataSource获取JDBC连接的静态方法。


并且以下方法应该是您要寻找的:


DataSourceUtils.getConnection(DataSource)
DataSourceUtils.getGetConnection(DataSource)


基本示例(来自MySQL documentation):

// Create a new application context. this processes the Spring config
ApplicationContext ctx = new ClassPathXmlApplicationContext("ex1appContext.xml");
// Retrieve the data source from the application context
DataSource ds = (DataSource) ctx.getBean("dataSource");
// Open a database connection using Spring's DataSourceUtils
Connection c = DataSourceUtils.getConnection(ds);
try {
    // retrieve a list of three random cities
    PreparedStatement ps = c.prepareStatement(
        "select City.Name as 'City', Country.Name as 'Country' " +
        "from City inner join Country on City.CountryCode = Country.Code " +
        "order by rand() limit 3");
    ResultSet rs = ps.executeQuery();
    while(rs.next()) {
        String city = rs.getString("City");
        String country = rs.getString("Country");
        System.out.printf("The city %s is in %s%n", city, country);
    }
} catch (SQLException ex) {
    // something has failed and we print a stack trace to analyse the error
    ex.printStackTrace();
    // ignore failure closing connection
    try { c.close(); } catch (SQLException e) { }
} finally {
    // properly release our connection
    DataSourceUtils.releaseConnection(c, ds);
}

07-21 19:48