Spring框架针对dao层的jdbcTemplate操作crud之add添加数据库操作

使用jdbcTemplate

原理是把加载驱动Class.forName("com.mysql.jdbc.Driver");

和连接数据库Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sw_database?user=root&password=root");

用一个对象完成DriverManagerDataSource dataSource=new DriverManagerDataSource();

org.springframework.jdbc.datasource.DriverManagerDataSource 这个应该称不上是连接池

(实现了javax.sql.DataSource接口,是Spring框架自带的数据源,不常用:每个连接请求时都新建一个连接,DriverManagerDataSource提供的连接没有进行池管理,当连接数到达一定的大小会出现异常)

package com.swift;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;
@Component(value="jdbcTemplateDemo")
public class JdbcTemplateDemo {
    public boolean add() {
        //设置数据库信息
        DriverManagerDataSource dataSource=new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/sw_database");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        
        //创建JdbcTemplate对象,设置数据源
        JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
        String sql="insert into sw_user(username,password) values(?,?)";
        int count=jdbcTemplate.update(sql, "doomsday","20171125");
        if(count==1) {
            return true;
        }
        return false;
    }
}

数据源可在xml中配置

    <bean id="driverManagerDateSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql:///springtest" />
        <property name="username" value="root" />
        <property name="password" value="abc"></property>
    </bean>

添加数据库操作使用JdbcTemplate对象根据数据源直接使用update方法完成,比之前简便很多。

之前完成需按下边方法:

PreparedStatement ps=conn.prepareStatement("insert into sw_user(username,password) values(?,?)");

ps.setString(1,“doomsday”);

ps.setString(2, “20171125”);

//ResultSet rs=ps.executeQuery();(不是这句,这句用于查询)

int count=ps.executeUpdate();

 if(count==1) {return true;}


 

上边代码使用Spring框架注解生成对象方法

xml配置文件代码如下:

<?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="com.swift"></context:component-scan>
     
</beans>

使用Servlet类进行测试:

package com.swift;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@WebServlet("/ServletTest")
public class ServletTest extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public ServletTest() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().append("Served at: ").append(request.getContextPath());
        ApplicationContext context=new ClassPathXmlApplicationContext("beanZhujie.xml");
        JdbcTemplateDemo jdbcTemplateDemo=(JdbcTemplateDemo) context.getBean("jdbcTemplateDemo");
        if(jdbcTemplateDemo.add()) {
            response.getWriter().append("帐号注册成功");
        }else {
            response.getWriter().append("注册失败");
        }
        
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

浏览器中的到结果如下:

navicat premium 中成功添加数据,结果如下:

 

posted @ 2017-11-25 17:45  Advancing-Swift  阅读(1220)  评论(0编辑  收藏  举报