First, create a spring project
Project Name: spring101302
Ii. adding a jar package to the project
1. Create a Lib directory in your project
/lib
2. Add spring support under the Lib directory
Commons-logging.jar
Junit-4.10.jar
Log4j.jar
Mysql-connector-java-5.1.18-bin.jar
Spring-beans-3.2.0.release.jar
Spring-context-3.2.0.release.jar
Spring-core-3.2.0.release.jar
Spring-expression-3.2.0.release.jar
Spring-jdbc-3.2.0.release.jar
Spring-tx-3.2.0.release.jar
Com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
Iii. Adding a configuration file to a project
1. Create the Conf directory in your project
2. Add the Spring core configuration file under the Conf directory
Configuration file name: Applicationcontext.xml
Configuration file Contents:
<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xmlns:context= "Http://www.springframework.org/schema/context"
Xsi:schemalocation= "
Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " >
<!--1. Configure the database connection pool--
<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name= "Jdbcurl" value= "jdbc:mysql://localhost:3306/spring" ></property>
<property name= "Driverclass" value= "Com.mysql.jdbc.Driver" ></property>
<property name= "User" value= "root" ></property>
<property name= "Password" value= "root" ></property>
</bean>
<!--2. Configure JdbcTemplate-
<bean id= "JdbcTemplate" class= "Org.springframework.jdbc.core.JdbcTemplate" >
<!--inject values to attributes--
<property name= "DataSource" ref= "DataSource" ></property>
</bean>
</beans>
Iv. Testing
1. Create the test directory on the project
/test
2. Creating a test package under the test directory
Package Name: Cn.jbit.spring101301.test
3. Create a test class under a test package
Test class Name: Jdbctemplatedemo.java
Test the contents of the class:
public class Jdbctemplatedemo {
/**
* Add data using spring JdbcTemplate
*/
@Test
public void Testjdbctemplate () {
ApplicationContext context = new Classpathxmlapplicationcontext ("Classpath:applicationContext.xml");
JdbcTemplate JdbcTemplate = (jdbctemplate) context.getbean ("JdbcTemplate");
String sql = "INSERT into temp (tid,tname) VALUES (3, ' Wangwu ')";
Jdbctemplate.execute (SQL);
}
}
This article is from the "Yan" blog, please be sure to keep this source http://suyanzhu.blog.51cto.com/8050189/1563221
spring-using a configuration file to complete the JdbcTemplate operations database-c3p0