gpt4 book ai didi

spring - 在Spring JDBC中通过JNDI获取JDBC连接

转载 作者:行者123 更新时间:2023-12-04 13:35:10 33 4
gpt4 key购买 nike

这个page on Spring JDBC

The DataSourceUtils class … provides static methods to obtain connections from JNDI



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

我想念什么?

最佳答案

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

Helper class that provides static methods for obtaining JDBC Connections from a DataSource.



并且以下方法应该是您要寻找的:
  • 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);
    }

    关于spring - 在Spring JDBC中通过JNDI获取JDBC连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3672794/

    33 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com