Spring 连接数据库测试
1.编写测试对象类
package model; import java.io.Serializable; /**
* Created by xumao on 2016/12/5.
*/
public class User implements Serializable{
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(int id, String name, String password) {
super();
this.id = id;
this.name = name;
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
}
public User() {
super();
} }
2.加入数据库配置db.properties
#数据库配置
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xumao?useUnicode=true&characterEncoding=utf8
user=root
password=xumao
3.配置文件
<?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">
<context:component-scan base-package="model,test"></context:component-scan> <!-- 配置外部资源 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- <util:properties id="dbProperties" location="classpath:db.properties"></util:properties> --> <!-- 配置dbcp连接池 -->
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSourceFactory"
factory-method="createDataSource">
<constructor-arg ref="dbProperties"/>
</bean> --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${url}"></property>
<property name="password" value="${password}"></property>
<property name="user" value="${user}"></property>
<property name="driverClass" value="${driver}"></property>
</bean> <!-- 配置jdbcTamplate -->
<bean id="jdbcTamplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> </beans>
4.测试类
package test; import model.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; /**
* Created by xumao on 2016/12/5.
*/
public class TestUser {
ClassPathXmlApplicationContext cx;
JdbcTemplate jdbcTemplate;
{
cx=new ClassPathXmlApplicationContext("springJdbcBean.xml");
//加载配置;
jdbcTemplate=cx.getBean(JdbcTemplate.class);
}
//测试jdbc连接;
@Test
public void testDataSource(){
//引入配置文件中的dataSource,与数据库连接;
DataSource dataSource=(DataSource) cx.getBean("dataSource");
System.out.println(dataSource);
}
//测试jdbcTemplate优化数据库;
@Test
public void jdbcTemplate(){
System.out.println(jdbcTemplate);
}
//测试用户的增加;
@Test
public void userAdd(){
String sql="insert into user values(?,?,?)";
try {
jdbcTemplate.update(sql,8,"测试2","123456");
System.out.println("用户添加成功");
} catch (Exception e) {
System.out.println("用户添加失败");
}
}
//测试用户的删除;
@Test
public void userDel(){
String sql="delete from user where id=?";
try {
jdbcTemplate.update(sql,5);
System.out.println("用户删除成功");
} catch (Exception e) {
System.out.println("用户删除失败");
}
}
//测试用户的修改;
@Test
public void userUpd(){
String sql="update user set name=? where id=?";
try {
jdbcTemplate.update(sql,"关羽",7);
System.out.println("用户修改成功");
} catch (Exception e) {
System.out.println("用户修改失败");
}
}
//测试用户的查询,根据用户的id;
@Test
public void userSelById(){
String sql="select * from user where id=?";
try {
//RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
User u=jdbcTemplate.queryForObject(sql, new RowMapper<User>() { @Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User u=new User();
u.setId(rs.getInt("id"));
String result=null;
if(rs.getString("name")!=null){
try{
result = new String(rs.getString("name").getBytes(),"utf-8");
}catch(Exception e){
result = null;
}
}
u.setName(result);
u.setPassword(rs.getString("password"));
return u;
}
},8);
System.out.println(u);
System.out.println("用户查询成功");
} catch (Exception e) {
System.out.println("用户查询失败");
System.out.println(e.getMessage());
}
}
// @Test
// public void userSelsById(){
// String sql="select * from user where id=?";
// try {
////RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
// List<User> u=jdbcTemplate.query(sql);
//// {
////
//// @Override
//// public User mapRow(ResultSet rs, int arg1) throws SQLException {
//// User u=new User();
//// u.setId(rs.getInt("id"));
//// u.setName(rs.getString("name"));
//// u.setPassword(rs.getString("password"));
//// return u;
//// }
//// },2);
// System.out.println(u);
// System.out.println("用户查询成功");
// } catch (Exception e) {
// System.out.println("用户查询失败");
// System.out.println(e.getMessage());
// }
// }
//测试用户的批量添加;
@Test
public void userManyAdd(){
String sql="insert into user values(?,?,?)";
//添加列表;
List<Object[]> userAdd=new ArrayList<Object[]>();
userAdd.add(new Object[]{1,"小明","123456"});
userAdd.add(new Object[]{2,"张飞","123456"});
userAdd.add(new Object[]{3,"刘备","123456"});
try {
jdbcTemplate.batchUpdate(sql, userAdd);
System.out.println("批量用户添加成功");
} catch (Exception e) {
System.out.println("批量用户添加失败");
}
}
//查询用户id大于7的用户的信息;
@Test
public void userQuery(){
String sql="select * from user where id>?";
//调用jdbcTemplate的方法,重写mapRow的方法;
try {
List<User> users=jdbcTemplate.query(sql, new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int arg1) throws SQLException {
User u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
return u;
}
},7);
System.out.println(users);
System.out.println("用户查询成功");
} catch (Exception e) {
System.out.println("用户查询失败");
System.out.println(e.getMessage());
}
}
}
问题总结:
1.缺少包 :之前使用的是一个集成的spring的包,但是其中还是少了一些jar包,加c3p0的包;
2.数据库乱码问题,这个问题现在还没很好的解决啊,数据库是用命令行的,程序端插入的中文在命令行窗口还是乱码的,取出的数据是正常的。现在IDEA的编码格式是utf-8,数据库设置了utf-8但是没有生效,再次启动还是会变,
mysql> show variables like '%char%';
+--------------------------+---------------------------------------------------------+
| Variable_name | Value |
+--------------------------+---------------------------------------------------------+
| character_set_client | latin1 |
| character_set_connection | latin1 |
| character_set_database | latin1 |
| character_set_filesystem | binary |
| character_set_results | latin1 |
| character_set_server | latin1 |
| character_set_system | utf8 |
| character_sets_dir | C:\Program Files\MySQL\MySQL Server 5.1\share\charsets\ |
+--------------------------+---------------------------------------------------------+
8 rows in set (0.00 sec)
Spring 连接数据库测试的更多相关文章
- Spring连接数据库的几种常用的方式
本文简单的讲解使用Spring连接数据库的几种常用方法: 测试主类为: package myspring2; import java.sql.*; import javax.sql.DataSourc ...
- Spring TestContext测试框架搭建
同样是测试,JUnit和Spring TestContext相比,Spring TestContext优势如下: 1.Spring TestContext可以手动设置测试事务回滚,不破坏数据现场 2. ...
- Spring引用测试
上下文 using System; using Spring.Core; using Spring.Aop; using System; using Spring.Core; using Spring ...
- 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建三:配置spring并测试
这一部分的主要目的是 配置spring-service.xml 也就是配置spring 并测试service层 是否配置成功 用IntelliJ IDEA 开发Spring+SpringMVC+M ...
- spark之JDBC开发(连接数据库测试)
spark之JDBC开发(连接数据库测试) 以下操作属于本地模式操作: 1.在Eclipse4.5中建立工程RDDToJDBC,并创建一个文件夹lib用于放置第三方驱动包 [hadoop@CloudD ...
- Spring MVC测试框架
原文链接:http://jinnianshilongnian.iteye.com/blog/2004660 Spring MVC测试框架详解——服务端测试 博客分类: springmvc杂谈 spri ...
- Spring MVC测试框架详解——服务端测试
随着RESTful Web Service的流行,测试对外的Service是否满足期望也变的必要的.从Spring 3.2开始Spring了Spring Web测试框架,如果版本低于3.2,请使用sp ...
- Spring Boot(七):spring boot测试介绍
首先maven要引入spring-boot-starter-test这个包. 先看一段代码 @RunWith(SpringRunner.class) @SpringBootTest(webEnviro ...
- spring 学习(一):使用 intellijIDEA 创建 maven 工程进行 Spring ioc 测试
spring学习(一):使用 intellijIDEA 创建 maven 工程进行 Spring ioc 测试 ioc 概念 控制反转(Inversion of Control,缩写为IOC),是面向 ...
随机推荐
- mahout分类
分类看起来比聚类和推荐麻烦多了 分类算法与聚类和推荐算法的不同:必须是有明确结果的,必须是有监督的,主要用于预测和检测 Mahout的优势 mahout的分类算法对资源的要求不会快于训练数据和测试数据 ...
- POJ 1159 Palindrome(LCS)
题目链接:http://poj.org/problem?id=1159 题目大意:给定一串字符,添加最少的字符,使之成为回文串. Sample Input 5 Ab3bd Sample Output ...
- windows进程函数试炼
实践一下windows进程相关函数: 代码如下: // test__getinformation.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h&quo ...
- thinkphp框架使用心得
接触的第一个PHP框架就是TP,在使用的了一段时间后就放弃了,说实话TP的弊端挺多,之后又接触laravel框架,慢慢的就爱上laravel这个框架了.这段时间由于公司的原因,又不得不使用thinkp ...
- 不错的轮播插件flexslider
http://flexslider.woothemes.com/ $('.flexslider').flexslider({ animation:'slide', //滑动效果:翻页效果,默认为fad ...
- git 基础命令
1.git init git 初始化仓库 2.git add . git 添加全部文件 3.git add xxx.txt git 添加单独文件 4.git commit -m "提交的 ...
- hexdump——Linux系统的二进制文件查看工具
hexdump是Linux下的一个二进制文件查看工具,可以将二进制文件转换为ASCII.10进制.16进制或8进制进行查看. 首先我们准备一个测试用的文件test,十六进制如下: 00 01 02 0 ...
- Java IO学习总结
Java IO流学习总结 Io流的内容比较多 ,大致可以分为字节流和字符流,其中为了提高效率又用到了缓冲区. Java流操作有关的类或接口: 流的概念和作用 流是一组有顺序的,有起点和终点的字节集合, ...
- .NET framework Chart组件SeriesChartType 枚举
成员名称 说明 Area 面积图类型. Bar 条形图类型. BoxPlot 盒须图类型. Bubble 气泡图类型. Candlestick K 线图类型. Column ...
- KeilC51使用详解 (二)
深入理解并应用C51对标准ANSIC的扩展是学习C51的关键之一.因为大多数扩展功能都是直接针对8051系列CPU硬件的.大致有以下8类: 8051存储类型及存储区域 存储模式 存储器类型声明 变量类 ...