第一步:在applicationContext.xml中配置dataSource和JdbcTemplate.
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
<property name="url"><value>jdbc:mysql://localhost:3306/laogan?useUnicode=true&characterEncoding=UTF-8</value></property>
<property name="username"><value>root</value></property>
<property name="password"><value>5856929</value></property>
</bean>
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
<property name="url"><value>jdbc:mysql://localhost:3306/laogan?useUnicode=true&characterEncoding=UTF-8</value></property>
<property name="username"><value>root</value></property>
<property name="password"><value>5856929</value></property>
</bean>
<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource"><ref bean="ds"></ref></property>
</bean>
<property name="dataSource"><ref bean="ds"></ref></property>
</bean>
第二部:编写Java类
public class Query(){
static ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
static JdbcTemplate jt=(JdbcTemplate)context.getBean("jdbctemplate");
static JdbcTemplate jt=(JdbcTemplate)context.getBean("jdbctemplate");
public static void main(String[] args) {
//用ResultSetExtractor处理结果
String sql="select * from 通讯录";
List list=new ArrayList();
list=jt.query(sql,new ResultSetExtractor(){
List list=new ArrayList();
list=jt.query(sql,new ResultSetExtractor(){
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
List list=new ArrayList();
while(rs.next()){
Person person=new Person();
person.setName(rs.getString("联系人"));
person.setPhone(rs.getString("电话号"));
list.add(person);
}});
return list;
}
List list=new ArrayList();
while(rs.next()){
Person person=new Person();
person.setName(rs.getString("联系人"));
person.setPhone(rs.getString("电话号"));
list.add(person);
}});
return list;
}
for(int i=0;i<list.size();i++){
Person person=(Person)list.get(i);
System.out.println(person.getName());
System.out.println(person.getPhone());
}
Person person=(Person)list.get(i);
System.out.println(person.getName());
System.out.println(person.getPhone());
}
}
}