本实例主要演示JdbcTemplate如何操作数据库(CRUD):
(1)、建立配置文件如下(applicationContext.xml):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "
http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/test</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value></value>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref local="dataSource"/>
</property>
</bean>
</beans>
==================================
(2)、编写测试类:
package com.xmddl.spring.test;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.*;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowCountCallbackHandler;
public class TestJdbcTemplate {
public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory bf=new XmlBeanFactory(resource);
JdbcTemplate jt=(JdbcTemplate)bf.getBean("jdbcTemplate");
---------------------------
建立一张表:jt.execute("create table myTemplate(id int,tempname varchar(100))");
---------------------------
插入一条记录:jt.execute("insert into myTemplate(id,tempname) values('001','xmddl')");
---------------------------
统计行数:int i=jt.queryForInt("select count(*) from mytemplate");
System.out.println(i);
---------------------------
查询结果集:List tempList=jt.queryForList("select * from mytemplate");
Iterator iter = tempList.iterator();
while (iter.hasNext()) {
Map item = (Map)iter.next();
System.out.println(item.get("id")+" "+item.get("tempname"));}
--------------------------
更新:jt.update("update mytemplate set tempname='zheli' where id='1'");
-------------------------
删除:jt.execute("delete from mytemplate where id='1'");
--------------------------
输出表中相关的信息:
RowCountCallbackHandler rcc=new RowCountCallbackHandler();
jt.query("select * from mytemplate",rcc);
System.out.println("columns sum:="+rcc.getColumnCount());
System.out.println("rows sum:="+rcc.getRowCount());
System.out.println("column name and type");
String[] name=rcc.getColumnNames();
int[] type=rcc.getColumnTypes();
for(int i=0;i<name.length;i++){
System.out.println("name"+i+" is:"+name[i]+" type"+i+" is"+type[i]);
}
-------------------------
(3)、小结:以上只是JdbcTemplate基本操作,权且当作入门,其实,只要是jdbc的操作,JdbcTemplate都提供了相应的接口操作。
JdbcTemplate操作数据库(CRUD)
最新推荐文章于 2024-04-19 08:00:00 发布