2017-07-10 45 views
0

我正在使用spring jdbc。我正在使用下面的代码来获得jdbc连接如何访问连接url

public void setDataSource(DataSource dataSource){ 
     this.dataSource = dataSource; 
     setJdbcTemplate(new JdbcTemplate(this.dataSource)); 
     setNamedParamdbcTemplate(new NamedParameterJdbcTemplate(this.dataSource)); 
     if(connectionUrl==null){ 
     Connection con; 

      try { 
       con = getJdbcTemplate().getDataSource().getConnection(); 
       connectionUrl = con.getMetaData().getURL(); 
      } catch (SQLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     } 
    } 

但我收到以下异常。

配置阻塞超时 (0 [毫秒])内没有可用的管理的连接

我具有由调试代码采取了打印。以上是getJdbcTemplate().getDataSource()代码的输出。

Click here for the image 如果我写了getJdbcTemplate().getDataSource().getConnection();以下例外即将到来。如何访问图像中存在的 connectionURL。

配置阻塞超时时间内没有可用的受管连接(0 [毫秒])

回答

0

您需要配置Spring上下文文件中的数据源与数据库连接的详细信息如下所示。

<bean id="dataSource" 
     class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
     <property name="url" value="jdbc:mysql://localhost:3306/testDB" /> 
     <property name="username" value="root" /> 
     <property name="password" value="root" /> 
    </bean> 

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 
     <property name="dataSource" ref="dataSource" /> 
    </bean> 

而要访问jdbcTemplate API,你需要注入你的java类。

@Repository 
public class EmployeeDAO{ 

    @Autowired 
    private JdbcTemplate jdbcTemplate; 

    public List<Emplyee> getEmployeeList(){ 
    //If you want to print the connection URL in your method 
    System.out.println("Connection URL: "+ jdbcTemplate.getDataSource().getConnection().getMetaData().getURL()); 
    } 
} 

这将打印的你已经在Spring上下文文件中配置的数据源的URL(JDBC:MySQL的://本地主机:3306/TESTDB)