简体   繁体   中英

Java JDBC Connection

I have created a servlet.xml file and declared jdbc properties in it . How do I access these properties in my code to establish the connection with database and execute the query?

This is datasource:

    <!--  Chicago JDBC Definitions 
  --> 
<beans:bean id="chdatasourceref" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
  <beans:property name="driverClass" value="com.mysql.jdbc.Driver" /> 
  <beans:property name="jdbcUrl" value="${chs.jdbcurl}" /> 
  <beans:property name="username" value="${chs.usr}" /> 
  <beans:property name="password" value="${chs.pass}" /> 
  <beans:property name="idleConnectionTestPeriod" value="6" /> 
  <beans:property name="idleMaxAge" value="600" /> 
  <beans:property name="maxConnectionsPerPartition" value="6" /> 
  <beans:property name="minConnectionsPerPartition" value="1" /> 
  <beans:property name="partitionCount" value="3" /> 
  <beans:property name="acquireIncrement" value="2" /> 
  <beans:property name="statementsCacheSize" value="200" /> 
  <beans:property name="releaseHelperThreads" value="2" /> 
  </beans:bean>
<!--  declare beans 
  --> 
<beans:bean id="chpartsdao" class="com.bvas.insight.jdbc.ChStocksDAOImpl">
  <beans:property name="chdataSource" ref="chdatasourceref" /> 
  </beans:bean>

How do I establish the connection from this source using jdbc and execute the query?

String sql = "SELECT distinct partno FROM vendorordereditems  WHERE orderno in (" + orders + " )"
            + " ORDER BY partno";

    PreparedStatement pstmt1 = null;
    ResultSet rs1 = null;

Get the bean in your application.

For example inject this bean in any of your service like below

@Inject
BoneCPDataSource chdatasourceref;

Now in your code, you can get the connection object, like below

Connection connection;
connection = chdatasourceref.getConnection();

Now you have connection object, you can fire any sql query using this connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM