<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.liyang"/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://X.X.X.X:X/dbname">
</property>
<property name="username" value="XX"></property>
<property name="password" value="XX"></property>
<property name="maxIdle" value="50"></property>
<property name="minIdle" value="10"></property>
</bean>
</beans>
package com.liyang;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
@Service
public class Main {
@Autowired
public static DataSource dataSource ;
public static void main(String[] args) {
String[] configLocations = {
"applicationContext-resource.xml" };
ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);
dataSource = (DataSource)context.getBean("dataSource") ;
Connection connection = null;
PreparedStatement ps = null;
try {
connection = dataSource.getConnection();
ps = getPreparedStatement(connection, "select * from XXX" , null) ;
ResultSet res = ps.executeQuery() ;
while(res.next()){
System.out.print(res.getDate(1) + " ") ;
System.out.print(res.getString(2) + " ") ;
System.out.println(res.getString(3)) ;
}
ps.close() ;
ps = null ;
connection.close() ;
connection = null ;
} catch (Exception e) {
System.out.println("ero1") ;
} finally {
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
System.out.println("ero2") ;
}
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
System.out.println("ero3") ;
}
}
}
private static PreparedStatement getPreparedStatement(Connection connection,
String sql, Object... values) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql);
if (values != null) {
for (int i = 1; i <= values.length; i++) {
ps.setObject(i, values[i - 1]);
}
}
return ps;
}
}