springmvc+链接mysql_安装配置数据库mysql+springMVC 与数据库连接完成 检索,条件检索和插入...
新建表:Test-----右键Create Table-----在表中添加字段一、项目与数据库连接1.修改数据库登录用户名和密码,连接数据库context.xml(片段)type="javax.sql.DataSource"driverClassName="com.mysql.jdbc.Driver"username="root"password="root"url="jdbc:mysql://.
新建表:Test-----右键Create Table-----在表中添加字段
一、项目与数据库连接
1.修改数据库登录用户名和密码,连接数据库
context.xml(片段)
type="javax.sql.DataSource"driverClassName="com.mysql.jdbc.Driver"
username="root"
password="root"
url="jdbc:mysql://localhost:3306/test"
useUnicode="true"characterEncoding="UTF-8"
maxIdle="2"maxWait="5000"maxActive="4"/>
二、检索
分析:
在UserSqlMap.xml中查询表中userID为admin的字段,存入bean中
从bean中取出数据,附給frm,然后以它的值作为检索条件去数据库中检索
将DB中取出的字段传到login页面
//设置一个命名空间
parameterClass="cn.training.bean.UserBean" //parameterClass用来存放
resultClass="cn.training.bean.UserBean"> //将查询到的值放入resultClass中
SELECT
userid as userId //进行as转换将userid作为userId处理
FROM
user
WHERE
userid = "admin"
//SELECT执行 数据库查询语句,查询user表中userid为admin的数据
public class HelloWorldService {
@Autowired
QueryDAO queryDao; //一次性取出符合的列表数据
@Autowired
UpdateDAO updateDao; //更新数据
public UserBean searchUser(UserBean frm) { //从bean中取出数据,附給frm,然后以它的值作为检索条件去数据库中检索
frm = queryDao.executeForObject("User.selectUser", NULL, UserBean.class);
//将DB中检索到的值传到login页面中
return frm;
}
三、条件检索
分析:就是在检索的基础上附加一个条件。让检索内容变成自定义的,就是通过将输入的数据作为一个变量传给userid然后用bean设置获取其属性值。再用frm从bean中取出数据作为检索条件检索数据库的字段,再将值附給frm
实现代码如下:
UserSqlMap.xml(修改片段)
parameterClass="cn.training.bean.UserBean"
resultClass="cn.training.bean.UserBean">
SELECT
userid as userId
FROM
user
WHERE
userid = #userId#
HelloWorldService.java(片段)
public UserBean searchUser(UserBean frm) {
//从bean中取出数据,附給frm,然后以它的值作为检索条件去数据库中检索
frm = queryDao.executeForObject("User.selectUser", frm, UserBean.class);
//若检索到将DB中检索到的值传到login页面中
return frm;
}
四、插入:
分析:
1.加载一个insert方法
2.使用insert into语句插入输入的值
3.将输入的值更新到数据库
UserSqlMap.xml(增加片段)
insert into user values(#userId#)
//增加了一个insert插入标记,并用insert into 语句像数据库键入新的userID
HelloWorldController.java (增加insert )
@RequestMapping(value="/init",method=RequestMethod.POST)
publicString initLogin(UserBean userBean,Model model){
intinsert=helloWorldService.insert(userBean);
UserBean result=helloWorldService.searchUser(userBean);
model.addAttribute("userBean",result);
return"login";
}
HelloWorldService.java
publicintinsert(UserBean frm){
returnupdateDao.execute("User.userinfo",frm);
}
原文:http://my.oschina.net/u/2411768/blog/478635
更多推荐
所有评论(0)