(二)Spring框架之JDBC的基本使用(p6spy插件的使用)
- 案例一: 用Spring IOC方式使用JDBC
Test_2.java
package jdbc; import java.lang.Thread.State;
import java.sql.Connection;
import java.sql.Statement; import javax.sql.DataSource; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* 本类中的数据源dataSource成员属性是通过IOC方式注入,
* @author 半颗柠檬、
*
*/
public class Test_2 {
private DataSource dataSource; public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
} public void addUser() throws Exception{ String sql="insert into user value('111',15,'男')";
System.out.println(this.dataSource);
Connection conn=null;
Statement stat=null;
try {
conn=this.dataSource.getConnection();
System.out.println("conn="+conn);
stat=conn.createStatement();
stat.executeUpdate(sql); } catch (Exception e) {
e.printStackTrace();
}finally{
// conn.close();
// stat.close();
}
} public static void main(String[] args) throws Exception {
/*
* 这里不能用Test_2 test_2=new Test_2() 这种方法来获得Test_2对象,否则spring.xml里把DataSource注入到Test_2的成员变量dataSource将无效。
*/
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Test_2 test_2=(Test_2)context.getBean("test_2");
test_2.addUser(); } }
spring.xml
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <!-- test_2类中需要的配置 -->
<bean id="test_2" class="jdbc.Test_2">
<property name="dataSource" ref="dateSource"></property>
</bean>
<!-- end -->
- 其中org.springframework.jdbc.datasource.DriverManagerDataSource 类是用来设置数据源的。
结果:
- 案例二: 使用JdbcTemplate模版来使用jdbc。
- JdbcTemplate对数据库的操作在jdbc上面做了深层次的封装。
Test_3.java
package jdbc; import javax.sql.DataSource; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate; /**
* Spring对数据库的操作在jdbc上面做了深层次的封装,
* 使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。
* @author Administrator
*
*/
public class Test_3 {
private DataSource dataSouce; public void setDataSouce(DataSource dataSouce) {
this.dataSouce = dataSouce;
} public void addUser(){
String sql="insert into user value('222',15,'男')"; JdbcTemplate jdbcTemplate=new JdbcTemplate(this.dataSouce); jdbcTemplate.execute(sql); } public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Test_3 test_3=(Test_3)context.getBean("test_3"); test_3.addUser(); } }
spring.xml
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <!-- test_3类中需要的配置 -->
<bean id="test_3" class="jdbc.Test_3">
<property name="dataSouce" ref="dateSource"></property>
</bean>
<!-- end-->
结果:
- 案例三: 将JdbcTemplate作为成员属性,直接在类中使用。
Test_4.java
package jdbc; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate; /**
* pring.xml中将jdbctemplate模版注入到本类中,
* jdbctemplate模版中又需要注入一个数据源的对象。
* @author Administrator
*
*/
public class Test_4 { private JdbcTemplate jdbctemplate; public void setJdbctemplate(JdbcTemplate jdbctemplate) {
this.jdbctemplate = jdbctemplate;
} public void addUser(){
String sql="insert into user value('333',15,'男')";
this.jdbctemplate.execute(sql);
} public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Test_4 test_4=(Test_4)context.getBean("test_4");
test_4.addUser(); } }
spring.xml
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <!-- test_4类中需要的配置 -->
<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"></property>
</bean> <bean id="test_4" class="jdbc.Test_4">
<property name="jdbctemplate" ref="jdbctemplate"></property>
</bean>
<!-- end -->
结果:
案例四: 使用JdbcDaoSupport包来使用spring JDBC
- Test_5.java
package jdbc; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.support.JdbcDaoSupport; /**
* 使用JdbcDaoSupport包来使用spring JDBC
* JdbcDaoSupport是JDBC数据访问对象的超类。它与特定的数据源相关联。这个类最重要的功能就是使子类可以使用JdbcTemplate对象。
* @author 半颗柠檬、
*
*/
public class Test_5 extends JdbcDaoSupport{ private void addUser(){
String sql="insert into user value('555',15,'男')";
this.getJdbcTemplate().execute(sql);
} public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml"); Test_5 test_5=(Test_5)context.getBean("test_5");
test_5.addUser();
} }
- spring.xml
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <!-- test_5类中需要的配置 -->
<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"></property>
</bean> <!-- test_5类中需要的配置 -->
<bean id="test_5" class="jdbc.Test_5" >
<property name="jdbcTemplate" ref="jdbctemplate">
</property>
</bean>
结果:
- 案例五: spring jdbc 进行DML(DML 数据操作语言 (insert/update/delete 等语句))
Test_DML.java
package jdbc; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.support.JdbcDaoSupport; /**
* DML 数据操作语言 (insert/update/delete 等语句)。
*
* @author 半颗柠檬、
*
*/
public class Test_DML extends JdbcDaoSupport{
/**
* insert语句
*/
private void insert(){
String sql="insert into user values('666',15,'女')";
this.getJdbcTemplate().execute(sql);
} /**
*更新语句
*/
private void update() {
String sql="update user set sex='男' where userName='111'";
this.getJdbcTemplate().execute(sql);
} /**
* 删除语句
*/
private void delete() { String sql="delete from user where userName='111'";
this.getJdbcTemplate().execute(sql); } public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Test_DML test_DML=(Test_DML) context.getBean("test_DML"); test_DML.insert();
// test_DML.update();
// test_DML.delete(); }
}
spring.xml
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"></property>
</bean> <!-- test_DML类中需要的配置 -->
<bean id="test_DML" class="jdbc.Test_DML" >
<property name="jdbcTemplate" ref="jdbctemplate">
</property>
</bean>
<!-- end -->
结果:
- 案例六: spring jdbc 进行DDL(DDL 数据定义语言(create/drop/alter))
Test_DDL.java
package jdbc; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
* DDL 数据定义语言(create/drop/alter)
* @author 半颗柠檬、
*
*/
public class Test_DDL extends JdbcDaoSupport{
/*
*create语句
*/
private void create() {
String sql="create table abc (name int)";
this.getJdbcTemplate().execute(sql); }
/*
* drop语句
*/
private void drop() {
String sql="drop table abc";
this.getJdbcTemplate().execute(sql); }
/*
* alter语句
*/
private void alter() {
String sql="alter table abc add birthday date";
this.getJdbcTemplate().execute(sql);
} public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Test_DDL test_DDL=(Test_DDL)context.getBean("test_DDL");
test_DDL.create();
// test_DDL.drop();
// test_DDL.alter(); }
}
spring.xml
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"></property>
</bean> <!-- test_DDL类中需要的配置 -->
<bean id="test_DDL" class="jdbc.Test_DDL">
<property name="jdbcTemplate" ref="jdbctemplate"></property>
</bean>
<!-- end -->
结果:
- 案例七:spring JDBC 使用预处理语句
Test_prepared.java
package jdbc; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.support.JdbcDaoSupport; /**
* spring JDBC 的预编译语句
* 本类中有三种方式来处理预编译语句
* @author 半颗柠檬、
*
*/ public class Test_prepared extends JdbcDaoSupport { private void prepared_1() { String sql = "update user set age=?,sex=? where userName=?"; this.getJdbcTemplate().update(sql, new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, 105);
ps.setString(2, "女");
ps.setString(3, "张三"); } }); } private void prepared_2() {
final String sql = "update user set age=?,sex=? where userName=?";
this.getJdbcTemplate().update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement pstat = con.prepareStatement(sql); pstat.setInt(1, 1);
pstat.setString(2, "NONE");
pstat.setString(3, "张三"); return pstat;
}
}); } private void prepared_3() {
String sql = "update user set age=?,sex=? where userName=?";
Object[] obj={500,"女","张三"};
this.getJdbcTemplate().update(sql,obj); } public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Test_prepared test_prepared = (Test_prepared) context.getBean("test_prepared");
// test_prepared.prepared_1();
// test_prepared.prepared_2();
test_prepared.prepared_3(); }
}
spring.xml
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"></property>
</bean> <!-- test_prepared类中需要的配置 -->
<bean id="test_prepared" class="jdbc.Test_prepared">
<property name="jdbcTemplate" ref="jdbctemplate"></property>
</bean>
<!-- end -->
结果:
- 案例九:具名参数模版类NamedParameterJdbcTemplate来处理预编译语句,解决动态生成的预编译语句下标不好处理的问题。
Test_Prepared_Name.java
package jdbc; import java.util.HashMap;
import java.util.Map; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import bean.UserBean; /**
* 用具名参数模版类NamedParameterJdbcTemplate来处理预编译语句。 主要解决:在经典的 JDBC 用法中, SQL 参数是用占位符 ?
* 表示,并且受到位置的限制. 定位参数的问题在于, 一旦参数的顺序发生变化, 就必须改变参数绑定.SQL语句是通过动态拼凑产生的,下标索引不好确定。
* 本类中使用三种方法来解决上述问题
*
* @author 半颗柠檬、
*
*/
public class Test_Prepared_Name extends JdbcDaoSupport { /**
* NamedParameterJdbcTemplate,update(String sql,Map<String,?> map)
* @param sex
* @param age
* @param userName
*/
private void prepared_name_1(String sex, int age, String userName) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("sex", sex);
paramMap.put("userName", userName);
paramMap.put("age", age); String sql = "update user set userName=userName";
if (sex != null && !sex.equals("")) {
sql = sql + ", sex=:sex "; }
if (age != 0) { sql = sql + ",age=:age"; }
if (userName != null && !userName.equals("")) { sql = sql + " where userName=:userName";
} NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(this.getDataSource());
template.update(sql, paramMap); } /**
* NamedParameterJdbcTemplate,update(String sql,MapSqlParameterSource paramMap)
* @param sex
* @param age
* @param userName
*/
private void prepared_name_2(String sex, int age, String userName) { MapSqlParameterSource paramMap = new MapSqlParameterSource(); paramMap.addValue("sex", sex);
paramMap.addValue("age", age);
paramMap.addValue("userName", userName); String sql = "update user set userName=userName";
if (sex != null && !sex.equals("")) {
sql = sql + ", sex=:sex "; }
if (age != 0) { sql = sql + ",age=:age"; }
if (userName != null && !userName.equals("")) { sql = sql + " where userName=:userName";
} NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(this.getDataSource());
template.update(sql, paramMap);
} /**
* NamedParameterJdbcTemplate,update(String sql,BeanPropertySqlParameterSource paramMap)
* @param userbean
*/
private void prepared_name_3(UserBean userbean) {
BeanPropertySqlParameterSource paramMap = new BeanPropertySqlParameterSource(userbean); String sql = "update user set userName=userName";
if (userbean.getSex() != null && !userbean.getSex().equals("")) {
sql = sql + ", sex=:sex "; }
if (userbean.getAge() != 0) { sql = sql + ",age=:age"; }
if (userbean.getUserName() != null && !userbean.getUserName().equals("")) { sql = sql + " where userName=:userName";
} NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(this.getDataSource());
template.update(sql, paramMap);
} public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Test_Prepared_Name test_Prepared_Name = (Test_Prepared_Name) context.getBean("test_prepared_name");
// test_Prepared_Name.prepared_name_1(null, 155, "杨千嬅"); // test_Prepared_Name.prepared_name_2("未知", 108, "杨千嬅");
UserBean userbean = new UserBean("杨千嬅", 1211, "女1");
test_Prepared_Name.prepared_name_3(userbean); } }
spring.xml
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"></property>
</bean> <!-- test_prepared类中需要的配置 -->
<bean id="test_prepared_name" class="jdbc.Test_Prepared_Name">
<property name="jdbcTemplate" ref="jdbctemplate"></property>
</bean> <!-- end -->
结果:
- 案例八:spring JDBC 的几种查询操作,并返回各种类型的结果集。
Test_Query.java
package jdbc; import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.support.JdbcDaoSupport; import bean.UserBean;
/**
* spring JDBC 的几种查询操作,并返回各种类型的结果集
* @author 半颗柠檬、
*
*/
public class Test_Query extends JdbcDaoSupport{ /*
* 把查询结果为多行数据封装为一个List,List中每个对象为一个Map,Map中存放着数据库中每行的数据(以列名=值的形式)
*/
private void queryForList() {
String sql="select * from user";
List<Map<String,Object>> listMap= this.getJdbcTemplate().queryForList(sql); for(Map<String, Object> map:listMap){ System.out.println(map);
} } /*
* 把查询结果为单行数据封装为一个Map。
*/
private void queryForMap() {
String sql="select * from user where userName='李四'"; Map<String,Object> map=this.getJdbcTemplate().queryForMap(sql); System.out.println(map); } /**
* 把查询结果为单行(多行)数据封装为自定义Object类型
*/
private void queryForObject() {
/**
* 查询某个表中共有多少条数据,queryForObject(sql, requiredType) 中的requiredType只能为基本类型或者String类型(也不能是这些类型的数组),
* 否则报错,查询的结果也只能是查询某个表中某一列的数据且只能是一条数据,
*/
String sql="select count(1) from user";
Long rsCount= this.getJdbcTemplate().queryForObject(sql, Long.class); System.out.println(rsCount); } private void queryForBean() {
/**
* 将结果封装为一个List<bean >
* sping中的RowMapper可以将数据中的每一行数据封装成用户定义的类
*/
String sql="select * from user"; BeanPropertyRowMapper<UserBean> mapper=new BeanPropertyRowMapper<UserBean>(UserBean.class);
List<UserBean> userList=this.getJdbcTemplate().query(sql, mapper); for(UserBean user:userList){
System.out.println(user.getUserName());
} /**
* 将结果封装为单个Bean
*/ sql="select * from user where userName='杨千嬅'";
BeanPropertyRowMapper<UserBean> rowMapper=new BeanPropertyRowMapper<UserBean>(UserBean.class);
UserBean user=this.getJdbcTemplate().queryForObject(sql, rowMapper);
System.out.println(user.getUserName()+"年龄为:" +user.getAge());
} private void queryForPrepared() {
String sql="select * from user where userName like ?"; BeanPropertyRowMapper<UserBean> rowMapper=new BeanPropertyRowMapper<UserBean>(UserBean.class);
List<UserBean> userList=this.getJdbcTemplate().query(sql, new PreparedStatementSetter(){ public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, "%三");
} }, rowMapper); for(UserBean user:userList){ System.out.println(user.getUserName());
} } private void queryForPreparedName() {
String sql="select * from user where userName like :userName"; NamedParameterJdbcTemplate template=new NamedParameterJdbcTemplate(this.getDataSource()); BeanPropertyRowMapper<UserBean> rowMapper=new BeanPropertyRowMapper<UserBean>(UserBean.class);
UserBean userbean=new UserBean();
userbean.setUserName("%四");
BeanPropertySqlParameterSource sqlParameterSource=new BeanPropertySqlParameterSource(userbean); List<UserBean> userList= template.query(sql,sqlParameterSource , rowMapper); for(UserBean user:userList){
System.out.println(user.getUserName());
} } public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml"); Test_Query test_Query=(Test_Query) context.getBean("test_Query"); // test_Query.queryForList();
// test_Query.queryForMap();
// test_Query.queryForObject(); // test_Query.queryForBean();
// test_Query.queryForPrepared();
test_Query.queryForPreparedName();
}
}
spring.xml
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean> <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"></property>
</bean> <!-- test_Query类中需要的配置 -->
<bean id="test_Query" class="jdbc.Test_Query">
<property name="jdbcTemplate" ref="jdbctemplate"></property>
</bean>
<!-- end -->
结果:
- P6SPY 的作用: 我们知道预处理语句里包含?号,这不利于我们调试程序,P6SPY和spring配合可以显示真正的SQL语句。
- 步骤:
1、添加p6spy.jar。
2、将spy.properties放到src下,最后部署到类路径下。
3、修改spy.properties中的数据库驱动, driverlist=com.mysql.jdbc.Driver(根据自己的数据库类型,解开注释,这里使用mysql。)
4.修改sql日志的输出方式,第三个是输出到控制台,第四个是输出到文件。以下是设置为控制台输出
#specifies the appender to use for logging
#appender=com.p6spy.engine.logging.appender.Log4jLogger
appender=com.p6spy.engine.logging.appender.StdoutLogger
#appender=com.p6spy.engine.logging.appender.FileLogger
5.配置spring.xml
<bean id="dateSource" class="com.p6spy.engine.spy.P6DataSource">
<constructor-arg ref="dateSourcetarget"></constructor-arg>
</bean> <bean id="dateSourcetarget" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 推荐使用配置文件的方法来设置数据源的参数--> <constructor-arg index="0" name="driverClassName" value="com.mysql.jdbc.Driver"></constructor-arg>
<!-- xml文件中不能直接用&号,要用"&"取代,否则报错,如下 -->
<constructor-arg index="1" value="jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=UTF-8"></constructor-arg>
<constructor-arg index="2" name="username" value="root"></constructor-arg>
<constructor-arg index="3" name="password" value=""></constructor-arg>
</bean>
结果:
可见,如果有预编译语句,p6spy都会在控制台里打印出这个语句的完整句子。
以上所有例子源代码都在这里:链接
(二)Spring框架之JDBC的基本使用(p6spy插件的使用)的更多相关文章
- Spring框架的JDBC模板技术和事物
Spring框架的JDBC模板技术 技术分析之Spring框架的JDBC模板技术概述 1. Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单 ...
- Spring框架之jdbc源码完全解析
Spring框架之jdbc源码完全解析 Spring JDBC抽象框架所带来的价值将在以下几个方面得以体现: 1.指定数据库连接参数 2.打开数据库连接 3.声明SQL语句 4.预编译并执行SQL语句 ...
- Spring框架的JDBC模板技术概述
1. Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单 2. 提供了JDBC模板,Spring框架提供的 * JdbcTemplate类 3. Spring框架可以整 ...
- Spring 框架的JDBC模板技术
1. 概述 Spring 框架提供了很多持久层的模板类来简化编程; Spring 框架提供的JDBC模板类: JdbcTemplate 类; Spring 框架提供的整合 Hibernate 框架的模 ...
- 演示Spring框架的JDBC模板的简单操作
1. 步骤一:创建数据库的表结构 create database spring_day03; use spring_day03; create table t_account( id int prim ...
- 第一次玩博客,今天被安利了一个很方便JDBC的基于Spring框架的一个叫SimpleInsert的类,现在就来简单介绍一下
首先先对这段代码的简单介绍,我之前在需要操作JDBC的时候总是会因为经常要重新写SQL语句感到很麻烦.所以就能拿则拿不能拿的就简单地封装了一下. 首先是Insert.Spring框架的JDBC包里面的 ...
- Spring框架的第三天
## Spring框架的第三天 ## ---------- **课程回顾:Spring框架第二天** 1. IOC的注解方式 * @Value * @Resource(name="" ...
- Spring框架第一天
## 今天课程:Spring框架第一天 ## ---------- **Spring框架的学习路线** 1. Spring第一天:Spring的IOC容器之XML的方式,Spring框架与Web项目整 ...
- Spring框架之websocket源码完全解析
Spring框架之websocket源码完全解析 Spring框架从4.0版开始支持WebSocket,先简单介绍WebSocket协议(详细介绍参见"WebSocket协议中文版" ...
随机推荐
- Uber如何搭建一个基于Kafka的跨数据中心复制平台 原创: 徐宏亮 AI前线 今天
Uber如何搭建一个基于Kafka的跨数据中心复制平台 原创: 徐宏亮 AI前线 今天
- insmod某个内核模块时提示“Failed to find the folder holding the modules”如何处理?
答: 创建/lib/modules/$(uname -r)目录,命令如下: mkdir /lib/modules/$(uname -r)
- rand随机函数
1.rand() rand()函数是使用线性同余法做的,它并不是真的随机数,因为其周期特别长,所以在一定范围内可以看成随机的. rand()函数不需要参数,它将会返回0到RAND_MAX之间的任意的整 ...
- keras检查点的保存
来自 keras的文档:https://keras.io/callbacks/#callback ModelCheckpoint keras.callbacks.ModelCheckpoint(fil ...
- IO流的标准处理代码
FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("aaa.t ...
- 前后端分离session不一致问题
前端VUE.js 后端SSM 问题描述: 该项目的登录先由后台生成一验证码返回给前端,并保存在session中,不过当前端登录时,后台会报 NullPointerException,看前端的请求头才发 ...
- topK问题
概述 在N个乱序数字中查找第K大的数字,时间复杂度可以减小至O(N). 可能存在的限制条件: 要求时间和空间消耗最小.海量数据.待排序的数据可能是浮点型等. 方法 方法一 对所有元素进行排序,之后取出 ...
- sonar:windows重启sonar
登录后操作
- Ocelot+Consul 集群搭建实践
博客园已经有很多大神写过consul集群搭建了.大家都在玩,那我也不能托后退呢 不过自己研究下还是好的.毕竟每个人遇到的问题的不同 研究过才能说自己玩过consul,文章有部分名词解释是收集网络 Co ...
- html转图片网页截屏(三),puppeteer
puppeteer谷歌出品,是一个 Node 库,它提供了一个高级 API 来通过 DevTools 协议控制 Chromium 或 Chrome. 官方github地址:https://github ...