JdbcTemplate在spring中的使用
一、spring中内置的数据源
DriverManagerDataSource
JdbcTemplate的基础知识:https://www.cnblogs.com/cqyp/p/12433184.html
二、CRUD操作
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <!--DriverManagerDataSource:spring内置的数据源--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///spring"/> <property name="username" value="root"/> <property name="password" value="123"/> </bean>
public class JdbcTemplateDemo3 { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml"); JdbcTemplate template = ac.getBean("jdbcTemplate", JdbcTemplate.class); //保存 //template.execute("insert into account (name,money) values (?,?)","eee","456"); //更新 //template.update("update account set name=?,money=? where id=?","ccc","133",5); //删除 //template.update("delete from account where id=?",5); //查询所有 List<Account> accountList = template.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class)); accountList.forEach(account -> System.out.println(account)); //按id查询 List<Account> account = template.query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), 5); System.out.println(account.get(0)); //查询数量 Integer integer = template.queryForObject("select count(id) from account", Integer.class); } }