1.首先导入jdbc的三个包
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
2.配置jdbc.xml 和jdbc.properties
jdbc.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">
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
jdbc.properties
driver=com.mysql.jdbc.Driver
user=root
password=123456
url=jdbc:mysql://localhost/test?characterEncoding=utf8&useSSL=true&serverTimezone=UTC
3.使用ApplicationContext获取bean(person类的成员和表中的字段名相同,加上setter,getter)
public class Jdbc {
public static void main(String[] args) {
String sql = "UPDATE persons SET name = ? where id = ?";
ApplicationContext ctx = new ClassPathXmlApplicationContext("jdbc.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
jdbcTemplate.update(sql,"Lulu",3);//update
sql = "INSERT persons(name,age,sex) VALUE (?,?,?)";
List<Object[]> list= new ArrayList<>();
list.add(new Object[]{"aa",23,"male"});
list.add(new Object[]{"bb",24,"male"});
list.add(new Object[]{"cc",25,"male"});
jdbcTemplate.batchUpdate(sql,list);//批量插入
sql = "SELECT * FROM persons WHERE id = 1";
RowMapper<Person> rowMapper = new BeanPropertyRowMapper<>(Person.class);
Person person = jdbcTemplate.queryForObject(sql,rowMapper);
System.out.println(person);
sql = "SELECT * FROM persons WHERE id > 1";// id > 1 和id=1都可以使用query方法
RowMapper<Person> rowMapper = new BeanPropertyRowMapper<>(Person.class);
List<Person> persons = jdbcTemplate.query(sql,rowMapper);
System.out.println(persons);
sql = "select price from book where isbn>= ? ";
List<Integer> prices = jdbcTemplate.queryForList(sql,Integer.class,1001);
System.out.println(prices);
}
}