关于jdbcTemplate的一般操作及其CRUD

jdbcTemplate是spring为我们提供的一个操作数据库的模板类,其实就是对JDBC做了一层薄薄的封装。

使用它我们需要先导入这几个包:

spring-jdbc-4.2.4.RELEASE.jar、spring-orm-4.2.4.RELEASE.jar、spring-tx-4.2.4.RELEASE.jar以及数据库驱动包

然后我们可以这么用:

                DriverManagerDataSource ds = new DriverManagerDataSource();
		ds.setDriverClassName("com.mysql.jdbc.Driver");
		ds.setUrl("jdbc:mysql://127.0.0.1:3306/test");
		ds.setUsername("root");
		ds.setPassword("root");
		
		JdbcTemplate jt = new JdbcTemplate(ds);
                jt.execute("insert into user values (2,'tom',6)");

或者我们将其放到容器中随时可以取出来用:

        <bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
		<constructor-arg name="dataSource" ref="ds">		
		</constructor-arg>
	</bean>
	<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
                ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");	
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jt");
		jt.execute("insert into user values (2,'tom',6)");

CRUD:

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
		JdbcTemplate jt = (JdbcTemplate) ac.getBean("jt");
		jt.update("insert into user values (?,?,?)", 3,"Jack",9);
		jt.update("update user set name = ?,age=? where id = ?","Frank",8,3);
		jt.update("delete from user where id = ?",3);
                //查询所有
		List<User> users = jt.query("select * from user where age>?", new BeanPropertyRowMapper<User>(User.class), 1);
		for(User user : users){
			System.out.println(user);
		}
		//查询一个
		List<User> user = jt.query("select * from user where id = ?", new BeanPropertyRowMapper<User>(User.class), 1);
		System.out.println(user.isEmpty() ? "没有数据":user.get(0));
		//查询返回值是一行一列的情况
		Integer count = jt.queryForObject("select count(*) from user where id > ?", Integer.class, 1);
		System.out.println(count);

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值