package com.sp.person.sql.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.TreeMap;
import javax.sql.DataSource;
public class JdbcUtil {
private DataSource dataSource;
private boolean isMultipleDataSource;
private Map<String,DataSource> dataSources = new TreeMap<String,DataSource>();
private String dataSourceKey;
public JdbcUtil() {
}
public JdbcUtil(DataSource dataSource) {
this.dataSource = dataSource;
}
public ResultSet queryPageAbsolute(String sql,
int firstSize,int maxSize) throws SQLException {
PreparedStatement pre = this.getConn().prepareStatement(sql);
pre.setMaxRows(maxSize);
ResultSet rs = pre.executeQuery();
rs.absolute(firstSize * maxSize);
return rs;
}
public ResultSet queryPageRelative(String sql,
int firstSize,int maxSize) throws SQLException {
PreparedStatement pre = getConn().prepareStatement(sql);
pre.setMaxRows(maxSize);
ResultSet rs = pre.executeQuery();
rs.relative(firstSize);
return rs;
}
private Connection getConn() throws SQLException {
if (this.isMultipleDataSource) {
DataSource v_dataSource = this.queryDataSourceByKey();
if (v_dataSource != null) {
return v_dataSource.getConnection();
}
}
return this.dataSource.getConnection();
}
public DataSource queryDataSourceByKey() {
for (Map.Entry<String, DataSource> ds:this.dataSources.entrySet()) {
if (ds.getKey().equals(dataSourceKey)) {
return ds.getValue();
}
}
return null;
}
public DataSource queryDataSourceByKey(String useKey) {
for (Map.Entry<String, DataSource> ds:this.dataSources.entrySet()) {
if (ds.getKey().equals(useKey)) {
return ds.getValue();
}
}
return null;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public boolean isMultipleDataSource() {
return isMultipleDataSource;
}
public void setMultipleDataSource(boolean isMultipleDataSource) {
this.isMultipleDataSource = isMultipleDataSource;
}
public Map<String, DataSource> getDataSources() {
return dataSources;
}
public void setDataSources(Map<String, DataSource> dataSources) {
this.dataSources = dataSources;
}
public String getDataSourceKey() {
return dataSourceKey;
}
public void setDataSourceKey(String dataSourceKey) {
this.dataSourceKey = dataSourceKey;
}
}
|