本博客是使用spring框架简单整合JDBC,进行简单的数据库操作
1,导包:spring容器6个jar包+数据库驱动+c3p0连接池包+springt-aopx+Junit4包+sprint-test+spring-aop +spring-jdbc;
2,先直接编写一个JDBC木板,进行连接测试,
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/*
* 编写一个简单的jdbc木版进行测试
*/
public class Demo1 {
@Test
public void fun1() throws Exception {
//连接池
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///test");
dataSource.setUser("root");
dataSource.setPassword("AYZXX");
// 1 创建JDBC模板对象
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);
// 2 书写sql,并执行
String sql = "insert into t_user values(null,'李四') ";
jt.update(sql);
}
}
注意: 上面位置必须加@Test,并导入类库,才能进行Junit Test
2,测试成功,我们可以从下面junit看到一行绿色,表示你已经成功了,
3,下面着手配置到spring容器中,约束就不必说了。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="jdbc:mysql:///test"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="AYZXX"></property>
</bean>
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
可以对比jdbc模板进行配置,其中class配置:Ctrl + shift+t ,进行查找粘贴即可。
4,这样我们可以编写测试类,通过spring注解可直接向spring容器要jdbctemplate.然后进行增删改查操作:
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DemoSpring {
@Resource(name="jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Test
public void fun() {
String sql = "insert into t_user values(null,'李四') ";
jdbcTemplate.update(sql);
}
}
这样就是最基础的整合。
由于本人是刚入坑的新手难免有错误,希望包函。