一,
1,在resources中创建jdbc.propertise文件,文件后缀必须为propertise
jdbc.user=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false
jdbc.driver=com.mysql.cj.jdbc.Driver
2,在resources中创建bean.xml文件引入外部属性文件(上文的jdbc.propertise),创建数据源对象
<!-- 引入外部属性文件创建数据源对象-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
二,使用JdbcTemplate
注:配置属性类
package com.spring6.jdbc;
public class T_emp {
private String name;
private String sex;
private int age;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "T_emp{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
1,首先需要配置jdbcTemplate文件并装配数据源(前提是要先创建数据源对象)
<!-- 配置 JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 装配数据源 -->
<property name="dataSource" ref="druidDataSource"/>
</bean>
2,通过调用JdbcTemplate属性来使用
@Repository
public class BookDaoImpl implements BookDao{
@Autowired
private JdbcTemplate jdbcTemplate;
}
看尚硅谷学到的jdbcTemplate方法
update()方法能够使用增,删,改操作(update通俗易懂,方法第一个参数是sql语句,后面对应sql语句问号来进行填写就OK)
@Test
public void testUpdate() {
//增加操作
String insertSql = "insert into t_emp values(null,?,?,?)";
Object[] params = {"刘备", 24, "男"};
int insert = jdbcTemplate.update(insertSql, params);
System.out.println(insert);
// 修改操作
String updateSql = "update t_emp set name=? where id=?";
int update = jdbcTemplate.update(updateSql,"黄盖",1);
System.out.println(update);
//删除操作
String deleteSql="delete from t_emp where id=?";
int delete = jdbcTemplate.update(deleteSql, 2);
System.out.println(update);
queryForObject()方法能够使用查询方法,查询某行
jdbcTemplate.queryForObject(sql语句, new BeanPropertyRowMapper<>(属性类.class),查询的行);
以下为原理
T_emp tEmpResult = jdbcTemplate.queryForObject(selectSql,
(rs, rowNum) -> {
T_emp tEmp = new T_emp();
tEmp.setSex(rs.getString("sex"));
tEmp.setAge(rs.getInt("age"));
tEmp.setName(rs.getString("name"));
return tEmp;
}, 行数);
查询集合
@Test
public void ListSelcetTest(){
String sql="select * from t_emp where id=? ";
//查询集合
List<T_emp> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(T_emp.class),3);
//T_emp.class是属性类,3是查询的id
}
查询返回值
@Test
public void testSelectValue(){
String sql="select count(*) from t_emp ";//查询表t_emp有几个数据
Integer integer = jdbcTemplate.queryForObject(sql, Integer.class);
//Integer.class,为返回类型属性
}