Spring(三)——JDBC

1.概念

建立Java与MySQL的连接,在XML文件里配置显得更加灵活。(据说裸的JDBC很麻烦,没用过,具体也不清楚) 

2.导包

IOC的包+JdbcTemplate的+数据驱动和数据源的包,和AOP没有关系。

  • commons-logging
  • spring-beans
  • spring-context
  • spring-core
  • spring-expression(IOC)
  • spring-jdbc
  • spring-orm
  • spring-tx(JdbcTemplate)
  • druid(连接池,如果不用德鲁伊就用别的,下面会提到)
  • mysql-connector-java(数据驱动和数据源)

3.在XML里配置数据库和数据源

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 4      
 5     xmlns:p="http://www.springframework.org/schema/p"
 6     xmlns:util="http://www.springframework.org/schema/util"
 7     xmlns:context="http://www.springframework.org/schema/context"
 8     xsi:schemaLocation="
 9     http://www.springframework.org/schema/beans 
10      http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
11      
12      http://www.springframework.org/schema/util
13      http://www.springframework.org/schema/util/spring-util.xsd
14      
15      http://www.springframework.org/schema/context 
16      http://www.springframework.org/schema/context/spring-context-4.3.xsd
17      ">
18     
19         
20        <!-- 引入资源文件db.properties,以下两种方式选一种-->
21        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
22            <property name="Location" value="db.properties"></property>
23        </bean>
24        <!-- <context:property-placeholder location="db.properties"/> 
25         -->
26         
27        <!-- 创建并通过外部资源文件配置数据源,这里用了德鲁伊的数据源,
28        也可以用别的,例如org.springframework.jdbc.datasource.DriverManagerDataSource -->
29        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
30            <property name="driverClassName" value="${jdbc.driverClassName}"></property>
31            <property name="url" value="${jdbc.url}"></property>
32            <property name="username" value="${jdbc.username}"></property>
33            <property name="password" value="${jdbc.password}"></property>
34        </bean>
35        
36        <!-- 通过数据源配置JdbcTemplate -->
37        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
38            <property name="dataSource" ref="dataSource"></property><!-- 通过上面德鲁伊创建的数据源来 -->
39        </bean>
40    
41 </beans>

 

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=shoulinniao
资源文件db.properties

 

4.通过Java语言操作到MySQL数据库

package com.atguigu.jdbctemplate;

public class Emp {

    private Integer eid;
    private String ename;
    private Integer age;
    private String sex;
    public Integer getEid() {
        return eid;
    }
    public void setEid(Integer eid) {
        this.eid = eid;
    }
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "Emp [eid=" + eid + ", ename=" + ename + ", age=" + age + ", sex=" + sex + "]";
    }

}
/*
create table if not exists emp(
eid int auto_increment primary key,
ename varchar(20) ,
age int ,
sex varchar(10)
);
*/
Emp.java

 

    ApplicationContext ac=new ClassPathXmlApplicationContext("jdbc.xml");
    JdbcTemplate jdbcTemplate=ac.getBean("jdbcTemplate",JdbcTemplate.class);

(1)通过execute(String sql)来执行建表和删表语句

    @Test
    public void create() {
        String sql="create table if not exists emp("
                + "eid int auto_increment primary key,"
                + "ename varchar(20) ,"
                + "age int,"
                + "sex varchar(10)" + 
                ");";
        jdbcTemplate.execute(sql);
        System.out.println(sql);/*
        sql="drop table emp;";
        jdbcTemplate.execute(sql);
        System.out.println(sql);*/
    }

 

(2)通过update()方法来对表中记录执行增、删、改的操作

int update(String sql),直接写固定的一条语句,不用[?]之类的通配符,返回被影响的记录行数。例如

jdbcTemplate.update("  insert into emp values(null,'张三',23,'男');  ");

int update(String sql,Object args[0],Object args[1]...,Object args[n]),这个是用[?]替代数据,通过参数传递。

String sql="insert into emp values(null,?,?,?) ";
jdbcTemplate.update(sql,"李四",24,"男");

如果想要插入多条记录,用Object类型的二维数组将记录存起来,再遍历插入,如下,即可以批量处理

        String sql="insert into emp values(null,?,?,?) ";
        Object[][] objects=new Object[3][3];
        objects[0][0]="王五";
        objects[0][1]=24;
        objects[0][2]="男";
        objects[1][0]="赵六";
        objects[1][1]=29;
        objects[1][2]="男";
        objects[2][0]="胜七";
        objects[2][1]=28;
        objects[2][2]="男";
        for(int i=0;i<objects.length;i++)
            jdbcTemplate.update(sql,objects[i][0],objects[i][1],objects[i][2]);

String batchUpdate(String sql, ?),真批量处理,返回一个看不懂的东西。

List<Object[]>list=new ArrayList<Object[]>();
list.add(new Object[] {"王八",15,"男"});
list.add(new Object[] {"老九",14,"女"});
System.out.println(jdbcTemplate.batchUpdate(sql,list));//输出是[I@80ec1f8

还有一个拼接操作,举例正面反面案例,具体原因暂不清楚,先记着,好记性不如烂笔头。

        /*错误写法,这样只会删除eid=1的语句
        String eid="1,2,3";
        String sql="delete from emp where eid in (?)";
        jdbcTemplate.update(sql,eid);
        */
        //正确写法
        String eid="1,2,3";
        String sql="delete from emp where eid in ("+eid+")";
        jdbcTemplate.update(sql);

以上大概都是通过字符串拼接、替换实现。

(3)query()用于查询表中记录,需要存储(不然查了干嘛?)

RowMapper<Emp> map=new BeanPropertyRowMapper<Emp>(Emp.class);//这句代码是很重要,并且需要()加上Emp.class之类的东西,表示MySQL中表的列名/字段 与 Java中类的属性 建立映射关系。

queryForObject()用于查询单行记录,应该很少用,记两个样例先

        RowMapper<Emp> map=new BeanPropertyRowMapper<Emp>(Emp.class);
        String sql=" select * from emp where eid=?";
        Emp emp=jdbcTemplate.queryForObject(sql,new Object[] {5},map);//eid=?改成eid>?就报错了,所以只能是单行记录
        System.out.println(emp);
        sql="select count(*) from emp ";
        System.out.println(jdbcTemplate.queryForObject(sql, Integer.class));
        //这里可以Integer改为String、double等,就是不能改为Emp这样的类,表示返回类型。

List query(String sql,RowMapper map)返回一个结果集,可以包含多条记录

        RowMapper<Emp> map=new BeanPropertyRowMapper<Emp>(Emp.class);
        String sql=" select eid,ename,age from emp ";
        List<Emp> list=jdbcTemplate.query(sql, map);
        for(int i=0;i<list.size();i++)
            System.out.println(list.get(i));
        //输出:Emp [eid=4, ename=赵六, age=29, sex=null],sql语句中没有说要查sex所以是null

 

 


学习资料:B站尚硅谷Spring视频

 

posted @ 2020-05-22 21:36  守林鸟  阅读(172)  评论(0编辑  收藏  举报