博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Jdbc
阅读量:3963 次
发布时间:2019-05-24

本文共 12150 字,大约阅读时间需要 40 分钟。

Spring Jdbc

Jdbc Template

  • spring中的jdbc模块负责数据库资源管理和错误处理,简化对数据库的操作,
  • Spring框架提供了Jdbc Template类,它是Spring框架数据抽象层的基础,其他更高层次的抽象类都是建立在它的基础之上,Jdbc Template 是 Spring Jdbc 的核心类。
    在这里插入图片描述

Spring Jdbc 的配置

在这里插入图片描述

  • username;数据库用户名
  • password:数据库的密码
  • url:数据库所在地址
  • driverClassName:数据库驱动名称

常用的方法

execute()

  • 主要用于创建数据库的表

代码

applicationContext.xml

JdbcTemplateTest

package com.yzb.chapter04.example1;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.jdbc.core.JdbcTemplate;/** 使用execute()方法进行创建表的工作* */public class JdbcTemplateTest {    /*    * 第一种方式    * */    public static void main(String[] args) {        String path = "com/yzb/chapter04/example1/applicationContext.xml";        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);        JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");        //使用execute()方法执行SQL语句,创建用户账户管理表acount        jdbcTemplate.execute("create table account("+                "id int primary key auto_increment,"+                "uesrname varchar(50),"+                "balance double)");        System.out.println("将建用户表account成功");    }    /*    * 第二种方式:单元测试    * */    @Test    public static void mainTest() {        String path = "com/yzb/chapter04/example1/applicationContext.xml";        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);        JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");        //使用execute()方法执行SQL语句,创建用户账户管理表acount        jdbcTemplate.execute("create table account("+                "id int primary key auto_increment,"+                "uesrname varchar(50),"+                "balance double)");        System.out.println("将建用户表account成功");    }}

update()

  • int update(String Sql) : 直接执行传入的sql语句,返回受影响的sql语句的行数;
  • int update(String sql ,Object … args): args设置sql中设置的参数,返回受影响的行数;
  • int update(String sql ,PreparedStatementSetter pss): 通过PreparedStatementSetter设置SQL语句中的参数,并返回受影响的行数;
  • int update(PreparedStatementCreator psc):用于执行从PreparedStatementCreator返回的语句,放回受影响的行数。

Account

package com.yzb.chapter04.example2;public class Account {    private Integer id;    private String username;    private Double balance;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public Double getBalance() {        return balance;    }    public void setBalance(Double balance) {        this.balance = balance;    }    @Override    public String toString() {        return "Account{" +                "id=" + id +                ", username='" + username + '\'' +                ", balance=" + balance +                '}';    }}

AccountDao

package com.yzb.chapter04.example2;public interface AccountDao {    //添加账户    public int addAccount(Account account);//    更改用户    public  int updateAccount(Account account);    //删除用户    public int deleteAccount(int id );}

AccountDaoImpl

package com.yzb.chapter04.example2;import org.springframework.jdbc.core.JdbcTemplate;public class AccountDaoImpl implements AccountDao {    //声明JdbcTemplate属性以及setter方法    private JdbcTemplate jdbcTemplate;    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {        this.jdbcTemplate = jdbcTemplate;    }    //添加用户    @Override    public int addAccount(Account account) {        //定义SQL        String sql = "insert into account(username,balance) value(?,?)";        //定义一个数组存储sql中的参数        Object[] obj = {account.getUsername(),account.getBalance()};        //执行添加操作,返回的是受sql语句影响的记录条数        int update = jdbcTemplate.update(sql, obj);        return update;    }    //更改用户    @Override    public int updateAccount(Account account) {        //定义SQL        String sql = "update account set username=?,balance=? where id=?";        //定义一个数组存储sql中的参数        Object[] obj = {account.getUsername(),account.getBalance(),account.getId()};        //执行更改操作,返回的是受sql语句影响的记录条数        int update = jdbcTemplate.update(sql, obj);        return update;    }    //删除用户    @Override    public int deleteAccount(int id) {    //定义sql        String sql = "delete from account where id=?";        //执行更改操作,返回的是受sql语句影响的记录条数        int update = jdbcTemplate.update(sql, id);        return update;    }}

applicationContext.xml

UpdateTest

package com.yzb.chapter04.example2;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class UpdateTest {    public static void main(String[] args) {        //加载配置文件        String path = "com/yzb/chapter04/example2/applicationContext.xml";        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);        //获取AccountDao的实例        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");        //创建Account的对象        Account account = new Account();        account.setUsername("tom");        account.setBalance(1234.00);        int num = accountDao.addAccount(account);        if(num >0){            System.out.println("成功插入了"+num+"条数据");        }else {            System.out.println("插入失败");        }    }}

UpdateTest1

package com.yzb.chapter04.example2;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class UpdateTest1 {    public static void main(String[] args) {        //加载配置文件        String path = "com/yzb/chapter04/example2/applicationContext.xml";        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);        //获取AccountDao的实例        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");        //创建Account的对象        Account account = new Account();        account.setUsername("tom");        account.setId(1);        account.setBalance(1234.00);        int num = accountDao.updateAccount(account);        if(num >0){            System.out.println("成功修改了"+num+"条数据");        }else {            System.out.println("修改失败");        }    }}

UpdateTest2

package com.yzb.chapter04.example2;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class UpdateTest2 {    public static void main(String[] args) {        //加载配置文件        String path = "com/yzb/chapter04/example2/applicationContext.xml";        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);        //获取AccountDao的实例        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");        int num = accountDao.deleteAccount(1);        if(num >0){            System.out.println("成功删除了"+num+"条数据");        }else {            System.out.println("删除失败");        }    }}

query()

  • List query(String sql,RowMapper rowmapper):执行Spring类型提供的参数,并通过RowMapper(通过这个接口的实现类,在它的泛型中加入对应的JavaBean,括号里面加入javaBean.class)返回一个List类型的结果
  • RowMapper rowMapper = new BeanPropertyRowMapper(Account.class);
  • List query(String sql,Object[] args,RowMapper rowmapper):使用Object[]类似设置SQL语句中的参数,通过RowMapper的回调方法可以返回List类型的结果
  • queryForObject(String sql ,RowMapper rowmapper ,Object …args):将参数绑定到SQL语句中,并通过RowMapper返回一个Object类型的单行记录。
  • List Query(String sql ,PreparedStatementSetter pss,RowMapper rowmapper):根据提供的Spring类型的属性参数提供的SQL语句创建的PreparedStatement对象,并通过RowMapper返回一个List的结果集。
  • queryForList(String sql,Object[] args,class elementType):返回一个多行数据的结果。

代码

AccountDao

package com.yzb.chapter04.example2;import java.util.List;public interface AccountDao {    //添加账户    public int addAccount(Account account);//    更改用户    public  int updateAccount(Account account);    //删除用户    public int deleteAccount(int id );    //通过id查询    public Account findAccountById(int id);    //查询所有    public List
findAllAccount();}

UserDaoImpl

package com.yzb.chapter04.example2;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import java.util.List;public class AccountDaoImpl implements AccountDao {    //声明JdbcTemplate属性以及setter方法    private JdbcTemplate jdbcTemplate;    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {        this.jdbcTemplate = jdbcTemplate;    }    //添加用户    @Override    public int addAccount(Account account) {        //定义SQL        String sql = "insert into account(username,balance) value(?,?)";        //定义一个数组存储sql中的参数        Object[] obj = {account.getUsername(),account.getBalance()};        //执行添加操作,返回的是受sql语句影响的记录条数        int update = jdbcTemplate.update(sql, obj);        return update;    }    //更改用户    @Override    public int updateAccount(Account account) {        //定义SQL        String sql = "update account set username=?,balance=? where id=?";        //定义一个数组存储sql中的参数        Object[] obj = {account.getUsername(),account.getBalance(),account.getId()};        //执行更改操作,返回的是受sql语句影响的记录条数        int update = jdbcTemplate.update(sql, obj);        return update;    }    //删除用户    @Override    public int deleteAccount(int id) {    //定义sql        String sql = "delete from account where id=?";        //执行更改操作,返回的是受sql语句影响的记录条数        int update = jdbcTemplate.update(sql, id);        return update;    }    //通过ID查询账户    @Override    public Account findAccountById(int id) {        //定义sql语句        String sql ="select * from account where id=?";        //创建一个新的BeanPropertyRowMapper对象        RowMapper
rowMapper = new BeanPropertyRowMapper
(Account.class); //将id保定到sql语句中,通过RowMapper返回一个Object类型的单行记录 Account account = this.jdbcTemplate.queryForObject(sql, rowMapper, id); return account; } //查询所有的账户信息 @Override public List
findAllAccount() { //定义sql语句 String sql ="select * from account"; //创建一个新的BeanPropertyRowMapper对象 RowMapper
rowMapper = new BeanPropertyRowMapper
(Account.class); //执行静态的sql语句查询,通过RowMapper返回结果 List
query = this.jdbcTemplate.query(sql, rowMapper); return query; }}

UpdateTest3

package com.yzb.chapter04.example2;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class UpdateTest3 {    public static void main(String[] args) {        //加载配置文件        String path = "com/yzb/chapter04/example2/applicationContext.xml";        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);        //获取AccountDao的实例        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");        Account accountById = accountDao.findAccountById(2);        System.out.println(accountById);    }}

UpdatTest4

package com.yzb.chapter04.example2;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.List;public class UpdateTest4 {    public static void main(String[] args) {        //加载配置文件        String path = "com/yzb/chapter04/example2/applicationContext.xml";        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(path);        //获取AccountDao的实例        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");        List
allAccount = accountDao.findAllAccount(); for (Account account : allAccount) { System.out.println(account); } }}

转载地址:http://bzwki.baihongyu.com/

你可能感兴趣的文章
身份证的正确使用方法——非常重要的知识
查看>>
ExtJS & Ajax
查看>>
Tomcat在Windows下的免安装配置
查看>>
JMeter常用测试元件
查看>>
JMeter——使用技巧
查看>>
Hibernate 实体层设计--Table per subclass
查看>>
Ruby解决方案:The 'ffi' native gem requires installed build tools ; 含最新DevKit下载地址
查看>>
Python之操作MySQL数据库(二)
查看>>
简单介绍如何使用robotium进行自动化测试
查看>>
Python之操作XML文件
查看>>
eclipse+ADT 进行android应用签名详解
查看>>
Robotium只有apk文件例如Music.apk
查看>>
UI自动化测试框架对比(二)
查看>>
Selenium-webdriver系列教程(9)——如何操作select下拉框
查看>>
Selenium-webdriver系列教程(10)——如何智能的等待页面加载完成
查看>>
Robotium测试NotePad(一)
查看>>
Robotium测试NotePad(二) //测试添加文本
查看>>
Kafka 只有一个broker的例子
查看>>
ZooKeeper 精萃
查看>>
ZooKeeper 简介
查看>>