*在xml配置文件中
1. 配置c3p0连接池
<bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 注入属性值 -->
<!-- 每行的name固定写法 不可以改变 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost/testloginid"></property>
<property name="user" value="root"></property>
<property name="password" value="***123456"></property>
</bean>
对应在类中直接实现代码
ComboPooledDataSource dataSource =new ComboPooledDataSource();//创建类
try {
dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost/testloginid");
dataSource.setUser("root");
dataSource.setPassword("***123456");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
2.创建jdbc模板对象
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入c3p0值 -->
<property name="dataSource" ref="ds"></property>
</bean>
对应直接实现代码
JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);//创建JdbcTemplate类并注入一个ComboPooledDataSource类型数据也就是第一步配置的数据
3.在创建的类中注入JdbcTemplate对象
<bean id="JdbcTemplateDemo1" class="srj.testJdbc.JdbcTemplateDemo1">
<property name="jdbcTemplate" ref="JdbcTemplate"></property>
</bean>
java完整代码如下
xml文件名为 testxml.xml
java文件路径为 srj.testJdbc.JdbcTemplateDemo1
简单练习 没有分层直接在一个文件中实验
package srj.testJdbc;
import java.beans.PropertyVetoException;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JdbcTemplateDemo1 {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void add() {//实现的功能
/*
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost/testloginid");
dataSource.setUsername("root");
dataSource.setPassword("srj123456");
*/
/*ComboPooledDataSource dataSource =new ComboPooledDataSource();
try {
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost/testloginid");
dataSource.setUser("root");
dataSource.setPassword("srj123456");
} catch (PropertyVetoException e) {
e.printStackTrace();
}*/
/* JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);*/
String sql="insert into nuser(nusername,nuserpassword) values(?,?)";
int rows=jdbcTemplate.update(sql,"Edu","123456" );//影响的行数
System.out.println(rows);
}
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("testxml.xml");
JdbcTemplateDemo1 jd=(JdbcTemplateDemo1) ac.getBean("JdbcTemplateDemo1");//创建JdbcTemplateDemo1类并调用方法
jd.add();
}
}