JDBCTemplate操作数据库

1:创建对应数据库的  实体类(entity):

   

package JDBCTemplate.entity;

public class User {
    private String userId;
    private String username;
    private String ustatus;

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setUstatus(String ustatus) {
        this.ustatus = ustatus;
    }

    public String getUserId() {
        return userId;
    }

    public String getUsername() {
        return username;
    }

    public String getUstatus() {
        return ustatus;
    }
}

 

2:编写service和dao

  1)在dao里进行数据库操作

  2)调用jdbcTemplate里的update方法实现添加操作

  update(String sql,Object....args)

    update有两个参数:第一个是需要执行的sql语句,第二个是课变参数,可以有多个值,用来设置sql语句值

package JDBCTemplate.dao;

import JDBCTemplate.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BookdaoImpl implements BookDao{
    //注入JDBCTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //对数据库进行增加数据操作
    @Override
    public void add(Book book) {
        //创建sql语句
        String sql = "insert int book values(?,?,?)";
//        使用update执行
        int update = jdbcTemplate.update(sql, book.getUserId(), book.getUsername(), book.getUstatus());
//        update 是执行语句时影响的行数
        System.out.println(update);
    }
}

 

3:测试方法

package JDBCTemplate;

import JDBCTemplate.entity.Book;
import JDBCTemplate.service.Bookservice;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBook {

    @Test
    public void Testadd() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("file:E:\\IDE\\JavaEE\\src\\JDBCTemplate\\bean1.xml");

        Bookservice bookService = context.getBean("bookService", Bookservice.class);
        Book book = new Book();
        book.setUserId("1");
        book.setUsername("java");
        book.setUstatus("a");
        bookService.addBook(book);
    }
}

 

 

  

上一篇:Spring JdbcTemplate基本使用


下一篇:springboot+phoenix+mysql多数据源