Spring ~spring - jdbc

execute

  1. 准备

    1. 创建数据库

      
         CREATE DATABASE `spring` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_bin';
      
      
    2. 导入依赖

      
      <dependencies>
          <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-webmvc</artifactId>
              <version>5.3.9</version>
          </dependency>
          
          <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>4.11</version>
          </dependency>
      
          <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>8.0.26</version>
          </dependency>
          
          <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
          <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-jdbc</artifactId>
             <version>5.3.9</version>
          </dependency>
      </dependencies>
      
      
  2. 创建配置文件applicationContext.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"
              xsi:schemaLocation="http://www.springframework.org/schema/beans
               https://www.springframework.org/schema/beans/spring-beans.xsd">
       
           <!--1. 配置数据源-->
           <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
               <!--数据库驱动-->
               <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
               <!--连接数据库的url-->
               <property name="url" value="jdbc:mysql://localhost:3306/spring?useSSL = false&amp;serviceTimezone = GMT &amp; characterEncoding = utf-8"/>
               <!--连接数据库的用户名-->
               <property name="username" value="root"/>
               <!--连接数据库的密码-->
               <property name="password" value="root"/>
           </bean>
           <!--2.配置JDBC模板-->
           <bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
               <property name="dataSource" ref="dataSource"/>
           </bean>
       </beans>
    
    
  3. 测试

    
       package execute;
       
       import org.junit.Test;
       import org.springframework.context.ApplicationContext;
       import org.springframework.context.support.ClassPathXmlApplicationContext;
       import org.springframework.jdbc.core.JdbcTemplate;
       
       /**
        * @author 清川
        * @date 2021-09-20   21:52
        */
       public class TestExecute {
          
          
           @Test
           public void testExecute() {
          
          
               ApplicationContext context = new ClassPathXmlApplicationContext("execute/applicationContext.xml");
               JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
               jdbcTemplate.execute("create table account(" +
                       "id int primary key auto_increment," +
                       "username varchar(50)," +
                       "balance double)");
               /*String sql = "drop table  account;";
               jdbcTemplate.execute(sql);*/
               System.out.println("账户表account创建成功!");
           }
       }
    
    
    

update

  1. 新建pojo

       
       package update.pojo;
       
       /**
        * @author 清川
        * @date 2021-09-20   22:31
        */
       public class Account {
          
          
           //账户id
           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 +
                       '}';
           }
       }
    
    
    
  2. 新建dao及其impl

    
    package update.dao;
    
    import update.pojo.Account;
    
    /**
     * @author 清川
     * @date 2021-09-20   22:34
     */
    public interface AccountDao {
          
          
        //添加
        public int addAccount(Account account);
    
        //更新
        public int updateAccount(Account account);
    
        //删除
        public int deleteAccount(int id);
    }
    
    
    
    
    package update.dao;
    
    import org.springframework.jdbc.core.JdbcTemplate;
    import update.pojo.Account;
    
    /**
     * @author 清川
     * @date 2021-09-20   22:37
     */
    public class AccountDaoImpl implements AccountDao {
          
          
    
        //声明JdbcTemplate属性及其set方法
        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) values(?,?)";
            //定义数组,用于存储SQL语句的参数
            Object[] obj = new Object[]{
          
          
                    account.getUsername(),
                    account.getBalance()
            };
            //执行添加操作,返回值为受SQL语句影响的记录条数
            int num = this.jdbcTemplate.update(sql, obj);
            return num;
        }
    
        //更新账户
        @Override
        public int updateAccount(Account account) {
          
          
            //定义SQL
            String sql = "update account set username=?,balance=? where id = ?";
            //定义数组,用于存储SQL语句的参数
            Object[] params = new Object[]{
          
          
                    account.getUsername(),
                    account.getBalance(),
                    account.getId()
            };
            //执行添加操作,返回值为受SQL语句影响的记录条数
            int num = this.jdbcTemplate.update(sql, params);
            return num;
        }
    
        //删除账户
        @Override
        public int deleteAccount(int id) {
          
          
            //定义SQL
            String sql = "delete from account where id = ?";
            //执行添加操作,返回值为受SQL语句影响的记录条数
            int num = this.jdbcTemplate.update(sql, id);
            return num;
        }
    }
    
    
    
  3. 配置applicationContext.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"
              xsi:schemaLocation="http://www.springframework.org/schema/beans
               https://www.springframework.org/schema/beans/spring-beans.xsd">
       
           <!--1. 配置数据源-->
           <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
               <!--数据库驱动-->
               <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
               <!--连接数据库的url-->
               <property name="url"
                         value="jdbc:mysql://localhost:3306/spring?useSSL = false&amp;serviceTimezone = GMT &amp; characterEncoding = utf-8"/>
               <!--连接数据库的用户名-->
               <property name="username" value="root"/>
               <!--连接数据库的密码-->
               <property name="password" value="root"/>
           </bean>
           <!--2.配置JDBC模板-->
           <bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
               <property name="dataSource" ref="dataSource"/>
           </bean>
           <!--3. 配置注入类-->
           <bean class="update.dao.AccountDaoImpl" id="accountDao">
               <property name="jdbcTemplate" ref="jdbcTemplate"/>
           </bean>
       </beans>   
    
    
  4. 测试

       
       package update;
       
       import org.junit.Test;
       import org.springframework.context.ApplicationContext;
       import org.springframework.context.support.ClassPathXmlApplicationContext;
       import update.dao.AccountDao;
       import update.pojo.Account;
       
       /**
        * @author 清川
        * @date 2021-09-20   22:58
        */
       public class TestUpdate {
          
          
           @Test
           public void addAccountTest() {
          
          
               ApplicationContext context = new ClassPathXmlApplicationContext("update/applicationContext.xml");
               AccountDao accountDao = (AccountDao) context.getBean("accountDao");
               Account account = new Account();
               account.setUsername("tom");
               account.setBalance(1000.0);
               int num = accountDao.addAccount(account);
               if (num > 0) {
          
          
                   System.out.println("成功插入" + num + "条数据");
               } else {
          
          
                   System.out.println("插入失败!");
               }
           }
       
           @Test
           public void updateAccountTest() {
          
          
               ApplicationContext context = new ClassPathXmlApplicationContext("update/applicationContext.xml");
               AccountDao accountDao = (AccountDao) context.getBean("accountDao");
               Account account = new Account();
               account.setId(1);
               account.setUsername("tom");
               account.setBalance(2000.0);
               int num = accountDao.updateAccount(account);
               if (num > 0) {
          
          
                   System.out.println("成功修改" + num + "条数据");
               } else {
          
          
                   System.out.println("修改失败!");
               }
           }
       
           @Test
           public void deleteAccountTest() {
          
          
               ApplicationContext context = new ClassPathXmlApplicationContext("update/applicationContext.xml");
               AccountDao accountDao = (AccountDao) context.getBean("accountDao");
               int num = accountDao.deleteAccount(1);
               if (num > 0) {
          
          
                   System.out.println("成功删除" + num + "条数据");
               } else {
          
          
                   System.out.println("删除失败!");
               }
           }
       }
    
    
    

query

  1. 新建pojo

    
       package query.pojo;
       
       /**
        * @author 清川
        * @date 2021-09-20   22:31
        */
       public class Account {
          
          
           //账户id
           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 +
                       '}';
           }
       }
    
    
    
  2. 新建dao及impl

    
       package query.dao;
       
       import query.pojo.Account;
       
       import java.util.List;
       
       /**
        * @author 清川
        * @date 2021-09-20   22:34
        */
       public interface AccountDao {
          
          
           //通过id查询
           public Account findAccountById(int id);
           //查询所有账户
           public List<Account> findAllAccount();
       }
    
    
    
    
       package query.dao;
       
       import org.springframework.jdbc.core.BeanPropertyRowMapper;
       import org.springframework.jdbc.core.JdbcTemplate;
       import query.pojo.Account;
       
       import java.util.List;
       
       /**
        * @author 清川
        * @date 2021-09-20   22:37
        */
       public class AccountDaoImpl implements AccountDao {
          
          
       
           //声明JdbcTemplate属性及其set方法
           private JdbcTemplate jdbcTemplate;
       
           public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
          
          
               this.jdbcTemplate = jdbcTemplate;
           }
       
       
           @Override
           public Account findAccountById(int id) {
          
          
               //定义SQL语句
               String sql = "select * from account where id = ?";
               //创建一个新的BeanPropertyRowMapper对象
               BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
               return this.jdbcTemplate.queryForObject(sql,rowMapper,id);
           }
       
           @Override
           public List<Account> findAllAccount() {
          
          
               //定义SQL语句
               String sql = "select * from account";
               //创建一个新的BeanPropertyRowMapper对象
               BeanPropertyRowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
               return this.jdbcTemplate.query(sql,rowMapper);
           }
       }
    
    
    
  3. 配置applicationContext.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"
              xsi:schemaLocation="http://www.springframework.org/schema/beans
               https://www.springframework.org/schema/beans/spring-beans.xsd">
       
           <!--1. 配置数据源-->
           <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
               <!--数据库驱动-->
               <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
               <!--连接数据库的url-->
               <property name="url"
                         value="jdbc:mysql://localhost:3306/spring?useSSL = false&amp;serviceTimezone = GMT &amp; characterEncoding = utf-8"/>
               <!--连接数据库的用户名-->
               <property name="username" value="root"/>
               <!--连接数据库的密码-->
               <property name="password" value="root"/>
           </bean>
           <!--2.配置JDBC模板-->
           <bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
               <property name="dataSource" ref="dataSource"/>
           </bean>
           <!--3. 配置注入类-->
           <bean class="query.dao.AccountDaoImpl" id="accountDao">
               <property name="jdbcTemplate" ref="jdbcTemplate"/>
           </bean>
       </beans>
    
    
  4. 测试

    
       package query;
       
       import org.junit.Test;
       import org.springframework.context.ApplicationContext;
       import org.springframework.context.support.ClassPathXmlApplicationContext;
       import query.dao.AccountDao;
       import query.pojo.Account;
       
       import java.util.List;
       
       
       /**
        * @author 清川
        * @date 2021-09-20   22:58
        */
       public class TestQuery {
          
          
           @Test
           public void findAccountByIdTest() {
          
          
               ApplicationContext context = new ClassPathXmlApplicationContext("query/applicationContext.xml");
               AccountDao accountDao = (AccountDao) context.getBean("accountDao");
               Account account = accountDao.findAccountById(1);
               System.out.println(account);
           }
       
           @Test
           public void findAllAccountTest() {
          
          
               ApplicationContext context = new ClassPathXmlApplicationContext("query/applicationContext.xml");
               AccountDao accountDao = (AccountDao) context.getBean("accountDao");
               List<Account> allAccount = accountDao.findAllAccount();
               for (Account account : allAccount) {
          
          
                   System.out.println(account);
               }
           }
       
       }
    
    
    

猜你喜欢

转载自blog.csdn.net/m0_47585722/article/details/120402469