开发工具:
Sql server 2005
MyEclipse 6.0.1
开发步骤:
1.在数据库里建一个Test库,建一个Test表,表中含Id、Name、Description, 并insert 一些数据;
2.在MyEclipse 新建Web工程,命名为TestSpring_JdbcTemplate;
3.选择工程右击-->MyEclipse-->Add Spring Capabilities,勾选下些相关包;
4.在工程src里的applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver">
</property>
<property name="url"
value="jdbc:sqlserver://localhost:1433;databaseName=Test">
</property>
<property name="username" value="sa"></property>
<property name="password" value="sa"></property>
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate" abstract="false"
lazy-init="default" autowire="default" dependency-check="default">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
</beans>
5.在工程里建包com.sailing.spring, 再建一个Bean类和含main()方法的类。
JdbcTemplateTest.java
package com.sailing.spring;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowCountCallbackHandler;
/**
* Test spring jdbc template
* @author sailing
*/
public class JdbcTemplateTest {
/**
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Resource r = new ClassPathResource("applicationContext.xml");
BeanFactory bf = new XmlBeanFactory(r);
JdbcTemplate jt = (JdbcTemplate) bf.getBean("jdbcTemplate");
String sql = "select * from Test";
RowCountCallbackHandler rcch = new RowCountCallbackHandler();
jt.query(sql, rcch);
System.out.println("Rows=" + rcch.getRowCount()+ ",Count="+rcch.getColumnCount());
String[] columnName = rcch.getColumnNames();
for(String ss: columnName){
System.out.print(ss + ":");
}
List list = jt.queryForList(sql);
System.out.println(list.size());
Map map = new HashMap();
for(int i=0;i<list.size();i++){
map = (Map) list.get(i);
System.out.println("Id="+map.get("Id")+",Name="+map.get("Name")+",Desc="+map.get("Description"));
}
map = null;
/*** 3
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
***/
}
}
6.在JdbcTemplateTest.java以java application运行。
7.查看结果。