当前位置:Gxlcms > 数据库问题 > 安装配置数据库mysql+springMVC 与数据库连接完成 检索,条件检索和插入

安装配置数据库mysql+springMVC 与数据库连接完成 检索,条件检索和插入

时间:2021-07-01 10:21:17 帮助过:29人阅读

1.修改数据库登录用户名和密码,连接数据库

 context.xml (片段)

<Context>
<Resourcename="jdbc/TerasolunaSampleDataSource"
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"/>
</Context>

二、检索

分析:

  1. UserSqlMap.xml中查询表中userID为admin的字段,存入bean中

  2. 从bean中取出数据,附給frm,然后以它的值作为检索条件去数据库中检索

  3. 将DB中取出的字段传到login页面

<sqlMap namespace="User">                        //设置一个命名空间	
<select id="selectUser"		
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>
//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(修改片段)

<select id="selectUser"

parameterClass="cn.training.bean.UserBean"

resultClass="cn.training.bean.UserBean">

SELECT

userid as userId

FROM

user

WHERE

userid = #userId#

</select>

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 id="userinfo" parameterClass="cn.training.bean.UserBean">

insert into user values(#userId#)

</insert>

//增加了一个insert插入标记,并用insert  into 语句像数据库键入新的userID

 HelloWorldController.java (增加insert )

  @RequestMapping(value = "/init", method = RequestMethod.POST)

    public String initLogin(UserBean userBean, Model model) {

     int insert=helloWorldService.insert(userBean);

     UserBean result = helloWorldService.searchUser(userBean);

     model.addAttribute("userBean", result);

        return "login";

    }

 

HelloWorldService.java

public int insert(UserBean frm) {

return updateDao.execute("User.userinfo", frm);

}

 

 

安装配置数据库mysql+springMVC 与数据库连接完成 检索,条件检索和插入

标签:

人气教程排行