Spring对JDBC的操作——使用JdbcTemplate操作数据库(二)

使用具名参数的sql操作数据库。

具体配置跟Spring对JDBC的操作——使用JdbcTemplate操作数据库(一)的一样,只是在springxml文件配置中,要增加使用具名参数的相关配置。如下:

<!-- 添加配置NamedParameterJdbcTemplate具名参数 -->
	<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
		<constructor-arg ref="dataSource"></constructor-arg>
	</bean>

添加完后,进行相关的测试。下面列出了具名参数的两种使用方式。

ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
	NamedParameterJdbcTemplate npjt=ac.getBean(NamedParameterJdbcTemplate.class);
/**
	 * 使用具名参数为sql语句中的参数赋值,使用了map集合。
	 * **/
	@Test
	public void test4(){
		String sql="insert into Employee(name,email,did) values(:name,:email,:did)";
		Map<String, Object> map = new HashMap<>();
		map.put("name", "lala44");
		map.put("email", "[email protected]");
		map.put("did", 3);
		npjt.update(sql, map);
		}
	/**
	 * 使用具名参数进行sql参数赋值,利用到了类
	 * **/
	@Test
	public void test5(){
		String sql="insert into Employee(name,email,did) values(:name,:email,:did)";
		Employer e = new Employer();
		e.setName("test");
		e.setEmail("[email protected]");
		e.setDid(2);
		SqlParameterSource paramSource=new BeanPropertySqlParameterSource(e);
		npjt.update(sql, paramSource);
	}
发布了14 篇原创文章 · 获赞 0 · 访问量 4179

猜你喜欢

转载自blog.csdn.net/sky892012/article/details/104427855