Spring SqlRowSet example--转载

时间:2022-03-21 18:29:27

原文地址:http://www.roseindia.net/tutorial/spring/spring3/jdbc/sqlrowset.html

The 'SqlRowSet' is used to handle the result fetched (very similar to ResultSet in core java). The main difference is that SQL exception is never thrown by it. The 'SqlRowSet' throws 'org.springframework.jdbc.InvalidResultSetAccessException' if needed. For using it in your class file you need to import ' org.springframework.jdbc.support.rowset.SqlRowSet ' package. You can use next() and getString() method as you are using with 'ResultSet' of core java. Given below is example related to it :

sqlrowset.java

package net.roseindia;

import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet; public class sqlrowset {
private JdbcTemplate jdbcTemplate; public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
} public void doExecute() {
SqlRowSet srs =jdbcTemplate.queryForRowSet("select * from customer");
int rowCount = 0;
while (srs.next()) {
System.out.println(srs.getString("id") + " - " + srs.getString("first_name")+ " - " + srs.getString("last_name")+ " - " + srs.getString("last_login"));
rowCount++;
}
System.out.println("Number of records : "+rowCount);
} }

DataTable.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" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="CreateTable" class="net.roseindia.CreateTable">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlrowset" class="net.roseindia.sqlrowset">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://192.168.10.13:3306/ankdb" />
<property name="user" value="root" />
<property name="password" value="root" />
</bean>
<context:property-placeholder location="jdbc.properties" />
</beans>

sqlrowsetMain.java

package net.roseindia;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource; public class sqlrowsetMain { public static void main(String[] args) { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("DataTable.xml")); sqlrowset myBean = (sqlrowset) beanFactory.getBean("sqlrowset"); myBean.doExecute(); } }

OUTPUT

Data in Sql Table :

Spring SqlRowSet example--转载

After executing code output in Eclipse's console :

Spring SqlRowSet example--转载