简单使用
< bean id = " driverManagerDataSource" class = " org.springframework.jdbc.datasource.DriverManagerDataSource" >
< property name = " driverClassName" value = " com.mysql.jdbc.Driver" />
< property name = " url" value = " jdbc:mysql://localhost:3306/spring" />
< property name = " username" value = " root" />
< property name = " password" value = " 1234" />
</ bean>
@Test
public void test01 ( ) {
DriverManagerDataSource dataSource = new DriverManagerDataSource ( ) ;
dataSource. setDriverClassName ( "driver" ) ;
dataSource. setUrl ( "url" ) ;
dataSource. setUsername ( "username" ) ;
dataSource. setPassword ( "password" ) ;
JdbcTemplate template = new JdbcTemplate ( ) ;
template. setDataSource ( dataSource) ;
template. execute ( "update user set username = '张三' where id = 1 " ) ;
}
配置spring内置连接池
< bean id = " driverManagerDataSource" class = " org.springframework.jdbc.datasource.DriverManagerDataSource" >
< property name = " driverClassName" value = " com.mysql.jdbc.Driver" />
< property name = " url" value = " jdbc:mysql://localhost:3306/spring" />
< property name = " username" value = " root" />
< property name = " password" value = " 1234" />
</ bean>
< bean id = " jdbcTemplate" class = " org.springframework.jdbc.core.JdbcTemplate" >
< property name = " dataSource" ref = " driverManagerDataSource" />
</ bean>
@Autowired
@Qualifier ( "jdbcTemplate" )
private JdbcTemplate template;
@Test
public void test02 ( ) {
template. execute ( "update user set username = '李四' where id = 2 " ) ;
}
配置c3p0连接池
< bean id = " c3poDataSource" class = " com.mchange.v2.c3p0.ComboPooledDataSource" >
< property name = " dataSourceName" value = " com.mysql.jdbc.Driver" />
< property name = " jdbcUrl" value = " jdbc:mysql://localhost:3306/spring" />
< property name = " user" value = " root" />
< property name = " password" value = " 1234" />
</ bean>
< bean id = " jdbcTemplate" class = " org.springframework.jdbc.core.JdbcTemplate" >
< property name = " dataSource" ref = " c3p0DataSource" />
</ bean>
引入外部配置文件
jdbc.driverClass=driver
jdbc.jdbcUrl=url
jdbc.username=username
jdbc.password=password
< context: property-placeholder location = " classpath:db.properties" />
< bean id = " c3p0DataSource" class = " com.mchange.v2.c3p0.ComboPooledDataSource" >
< property name = " driverClass" value = " ${jdbc.driverClass}" />
< property name = " jdbcUrl" value = " ${jdbc.jdbcUrl}" />
< property name = " user" value = " ${jdbc.username}" />
< property name = " password" value = " ${jdbc.password}" />
</ bean>
< bean id = " jdbcTemplate" class = " org.springframework.jdbc.core.JdbcTemplate" >
< property name = " dataSource" ref = " c3p0DataSource" />
</ bean>
JdbcTemplate API
Spring JdbcTemplate方法详解