前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringJDBC

SpringJDBC

作者头像
用户3112896
发布2019-09-26 14:53:26
4440
发布2019-09-26 14:53:26
举报
文章被收录于专栏:安卓圈安卓圈安卓圈

除了Spring自带的Jar包,还要下载几个Jar包,这里我吐槽下CSDN,下个Jar包都要积分,真是想钱想疯了,其实可以Google得到

我把所有依赖的Jar包贴出来

MySql数据库的搭建和使用我就不说了,百度即可。现在的MySQL Workbench挺好用的

我们先来看下

普通的JDBC的写法

import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class JdbcDemo1 {
    @Test
    public void demo1() {
        //创建连接池
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///spring_database");
        dataSource.setUsername("root");
        dataSource.setPassword("1234");
        //创建jdbc模板
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.update("insert into account values (null,?,?)", "大傻", 10000d);
    }
}

下面是SpringJDBC写法

public class Account {
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

配置文件

applicationContext6.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">

    <!--引入属性文件-->
    <!--第一种方式:通过bean标签(很少用)-->
    <!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="location" value="classpath:jdbc.properties"/>
     </bean>-->
    <!--第二种方式:通过context标签引入-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置Spring内置的连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!--属性注入-->
        <property name="driverClassName" value="${jdbc.driverClass}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--配置DBCP连接池-->
   <!-- <bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>-->

    <!--配置C3P0连接池-->
    <!--<bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>-->

    <!--配置Spring的JDBC的模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_database
jdbc.username=root
jdbc.password=1234

执行

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext6.xml")
public class SpringJDBC {
    @Resource(name = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Test
    //保存操作
    public void demo() {
        jdbcTemplate.update("insert into account value (null,?,?)", "大静", 20000d);
    }

    @Test
    //修改操作
    public void demo1() {
        jdbcTemplate.update("update account set name = ?,money = ? where id = ?", "dbcp", 3000d, 4);
    }

    @Test
    //删除操作
    public void demo2() {
        jdbcTemplate.update("delete from account where id = ?", 6);
    }

    @Test
    //查询操作
    public void demo3() {
        String name = jdbcTemplate.queryForObject("select name from account where id = ?", String.class, 2);
        System.out.println("name=" + name);
    }

    @Test
    //统计个数
    public void demo4() {
        Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
        System.out.println("count=" + count);
    }

    @Test
    //封装到一个对象
    public void demo5() {
        Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new MyRowMapper(), 5);
        System.out.println(account);
    }

    @Test
    //查询多条记录
    public void demo6() {
        List<Account> list = jdbcTemplate.query("select * from account", new MyRowMapper());
        for (Account account : list) {
            System.out.println(account);
        }
    }

    class MyRowMapper implements RowMapper<Account> {

        @Override
        public Account mapRow(ResultSet resultSet, int i) throws SQLException {
            Account account = new Account();
            account.setId(resultSet.getInt("id"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getDouble("money"));
            return account;
        }
    }

}

Spring除了可以集成JDBC模板,还可以集成DBCP或者C3P0模板

执行结果就是在MySQL Workbench中查看

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 安卓圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档