[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[jfriends-ml 11036] javax.sql.RowSet の更新 可能サンプル実装
高橋(智)です。
読書会お疲れ様でした。
さて、本日のパターンで紹介されていた RowSet の実装ですが、
私が作成している MySQL用のJDBCドライバから、更新可能なRowSet
実装を汎用的に切り出したものを公開いたします。好きに使って下さ
いませ。
(※Webサイトにも掲載しておきます)
----------------------------------------------------------------------------------------------------------------
import java.io.*;
import java.math.*;
import java.sql.*;
import java.sql.Date;
import java.util.*;
import javax.naming.*;
import javax.sql.*;
public class MyRowSet implements RowSet, Serializable {
private static final int TRANSACTION_UNKNOWN = -1;
private String dataSourceName = null;
private Properties properties = null;
private String url = null;
private String username = null;
private String password = null;
private int transactionIsolation = MyRowSet.TRANSACTION_UNKNOWN;
private int queryTimeout = 0; // seconds
private int maxFieldSize = 0;
private int maxRows = 0;
private boolean readOnly = true;
private Map typemap = null;
private Vector listeners = new Vector();
private boolean escapeProcessing = false;
private String command = null;
private Object[] param_obj_array = null;
private int[] param_type_array = null;
private ArrayList rows = null;
private int index = 0;
private boolean last_null = false;
private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
private int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
private int fetchDirection = ResultSet.FETCH_UNKNOWN;
private int fetchSize = 0;
private ResultSetMetaData rs_meta = null;
private Hashtable columnName = null;
private Hashtable columnFullName = null;
private boolean onetable = true;
private Vector pk_cols = null;
private Object[] update_obj_array = null;
private int[] update_type_array = null;
private boolean insertmode = false;
private transient Connection updater = null;
public String getDataSourceName() {
return dataSourceName;
}
public void setDataSourceName(String name) throws java.sql.SQLException {
dataSourceName = name;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties prop) throws java.sql.SQLException {
properties = prop;
}
public String getUrl() throws java.sql.SQLException {
return url;
}
public void setUrl(String url) throws java.sql.SQLException {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String name) throws java.sql.SQLException {
username = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) throws java.sql.SQLException {
this.password = password;
}
public int getTransactionIsolation() {
return transactionIsolation;
}
public void setTransactionIsolation(int level) throws java.sql.SQLException {
transactionIsolation = level;
}
public int getQueryTimeout() throws java.sql.SQLException {
return queryTimeout;
}
public void setQueryTimeout(int seconds) throws java.sql.SQLException {
queryTimeout = seconds;
}
public void setConcurrency(int concurrency) throws java.sql.SQLException {
resultSetConcurrency = concurrency;
}
public void setType(int type) throws java.sql.SQLException {
resultSetType = type;
}
public int getMaxFieldSize() throws java.sql.SQLException {
return maxFieldSize;
}
public void setMaxFieldSize(int max) throws java.sql.SQLException {
maxFieldSize = max;
}
public int getMaxRows() throws java.sql.SQLException {
return maxRows;
}
public void setMaxRows(int max) throws java.sql.SQLException {
maxRows = max;
}
public boolean isReadOnly() {
return readOnly;
}
public void setReadOnly(boolean value) throws java.sql.SQLException {
readOnly = value;
}
public Map getTypeMap() throws java.sql.SQLException {
return typemap;
}
public void setTypeMap(Map map) throws java.sql.SQLException {
typemap = map;
}
public void addRowSetListener(RowSetListener listener) {
listeners.add(listener);
}
public void removeRowSetListener(RowSetListener listener) {
listeners.remove(listener);
}
public boolean getEscapeProcessing() throws java.sql.SQLException {
return escapeProcessing;
}
public void setEscapeProcessing(boolean enable) throws java.sql.SQLException {
if( enable )
throw new SQLException("mysql does not support setEscapeProcessing(true).");
escapeProcessing = enable;
}
public String getCommand() {
return command;
}
public void setCommand(String cmd) throws java.sql.SQLException {
command = cmd;
int param_count = 0;
StringTokenizer t_str = new StringTokenizer(command, "?", true);
while(t_str.hasMoreTokens())
{
String token = t_str.nextToken();
if( token.equals("?") )
param_count++;
}
param_obj_array = new Object[param_count];
param_type_array = new int[param_count];
int i;
for(i = 0; i < param_obj_array.length; i++)
param_obj_array[i] = null;
for(i = 0; i < param_type_array.length; i++)
param_type_array[i] = Types.NULL;
}
public void clearParameters() throws java.sql.SQLException {
if( param_obj_array != null &&
param_type_array != null )
{
int i;
for(i = 0; i < param_obj_array.length; i++)
param_obj_array[i] = null;
for(i = 0; i < param_type_array.length; i++)
param_type_array[i] = Types.NULL;
}
else
{
throw new SQLException("mysql error : clearParameters(), no parameter.");
}
}
private Connection getConnection() throws java.sql.SQLException {
if( dataSourceName != null )
{
try {
Context ctx = null;
if( properties != null )
ctx = new InitialContext(properties);
else
ctx = new InitialContext();
Object ref = ctx.lookup(dataSourceName);
if( ref == null )
throw new SQLException("Invalid DataSource Object!! : " + "null");
if( ref instanceof DataSource )
{
DataSource ds = (DataSource)ref;
if( username != null && password != null )
return ds.getConnection(username, password);
else
return ds.getConnection();
}
else if( ref instanceof ConnectionPoolDataSource )
{
ConnectionPoolDataSource cpds = (ConnectionPoolDataSource)ref;
if( username != null && password != null )
return cpds.getPooledConnection(username, password).getConnection();
else
return cpds.getPooledConnection().getConnection();
}
else if( ref instanceof XADataSource )
{
XADataSource xads = (XADataSource)ref;
if( username != null && password != null )
return xads.getXAConnection(username, password).getConnection();
else
return xads.getXAConnection().getConnection();
}
else
{
throw new SQLException("Invalid DataSource Object!! : " + ref.toString());
}
}
catch(Exception ex) {
throw new SQLException(ex.getMessage());
}
}
if( url != null )
{
if( username != null && password != null )
{
return DriverManager.getConnection(url, username, password);
}
else
{
if( properties != null )
return DriverManager.getConnection(url, properties);
else
return DriverManager.getConnection(url);
}
}
return null;
}
private void prepareSQLStatement(PreparedStatement stmt) throws java.sql.SQLException {
for(int i = 1; i <= param_obj_array.length; i++)
{
stmt.setObject(i, param_obj_array[i-1], param_type_array[i-1]);
}
}
private void buildResultSet(ResultSet rs) throws java.sql.SQLException {
resultSetType = rs.getType();
resultSetConcurrency = rs.getConcurrency();
rs_meta = rs.getMetaData();
int colnum = rs_meta.getColumnCount();
columnName = new Hashtable();
columnFullName = new Hashtable();
for(int i = 1; i <= colnum; i++)
{
String colname = rs_meta.getColumnName(i);
String colfull = rs_meta.getTableName(i) + "."+ colname;
Integer colno = new Integer(i-1);
columnName.put(colname, colno);
columnFullName.put(colfull, colno);
}
int rowcount = 0;
rows = new ArrayList();
while( rs.next() )
{
ArrayList vecrow = new ArrayList(colnum);
for(int i = 1; i <= colnum; i++)
{
Object obj = rs.getObject(i);
if( rs.wasNull() )
obj = null;
vecrow.add(obj);
}
rows.add(vecrow);
rowcount++;
if( maxRows != 0 && rowcount >= maxRows )
break;
}
}
private void initialUpdaters(ResultSet rs) throws java.sql.SQLException {
if( rs.getConcurrency() == ResultSet.CONCUR_UPDATABLE )
{
ResultSetMetaData meta = rs.getMetaData();
int colnum = meta.getColumnCount();
if( colnum >= 2 )
{
String tablename = meta.getTableName(1);
for(int i = 2; i <= colnum; i++)
{
if( !tablename.equals(meta.getTableName(i)) )
{
onetable = false;
break;
}
}
}
Connection conn = rs.getStatement().getConnection();
if( colnum >= 1 )
{
ResultSet primarykeys = conn.getMetaData().getPrimaryKeys("", "", meta.getTableName(1));
pk_cols = new Vector();
try {
while(primarykeys.next())
{
String colname = primarykeys.getString("COLUMN_NAME");
for(int i = 1; i <= colnum; i++)
{
String temp_colname = meta.getColumnName(i);
if( colname.equalsIgnoreCase(temp_colname) )
{
pk_cols.addElement(temp_colname);
break;
}
}
}
}
finally {
if( primarykeys != null )
{
try { primarykeys.close(); }
catch (Exception ex) { }
primarykeys = null;
}
}
}
update_obj_array = new Object[colnum];
update_type_array = new int[colnum];
}
}
public void execute() throws java.sql.SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
if( transactionIsolation != MyRowSet.TRANSACTION_UNKNOWN )
conn.setTransactionIsolation(transactionIsolation);
conn.setReadOnly(readOnly);
conn.setTypeMap(typemap);
stmt = conn.prepareStatement(command, resultSetType, resultSetConcurrency);
// stmt.setEscapeProcessing(escapeProcessing);
stmt.setFetchDirection(fetchDirection);
stmt.setFetchSize(fetchSize);
stmt.setMaxFieldSize(maxFieldSize);
stmt.setMaxRows(maxRows);
stmt.setQueryTimeout(queryTimeout);
prepareSQLStatement(stmt);
rs = stmt.executeQuery();
buildResultSet(rs);
initialUpdaters(rs);
}
finally {
if( rs != null )
{
try {
rs.close();
}
catch(Exception ex){}
}
if( stmt != null )
{
try {
stmt.close();
}
catch(Exception ex){}
}
if( conn != null )
{
try {
conn.close();
}
catch(Exception ex){}
}
}
}
public void setNull(int parameterIndex, int sqlType) throws java.sql.SQLException {
setObject(parameterIndex, null, sqlType);
}
public void setBoolean(int parameterIndex, boolean x) throws java.sql.SQLException {
throw new SQLException("mysql does not support setBoolean(int, boolean).");
}
public void setByte(int parameterIndex, byte x) throws java.sql.SQLException {
Byte obj = new Byte(x);
setObject(parameterIndex, obj, Types.TINYINT);
}
public void setShort(int parameterIndex, short x) throws java.sql.SQLException {
Short obj = new Short(x);
setObject(parameterIndex, obj, Types.SMALLINT);
}
public void setInt(int parameterIndex, int x) throws java.sql.SQLException {
Integer obj = new Integer(x);
setObject(parameterIndex, obj, Types.INTEGER);
}
public void setLong(int parameterIndex, long x) throws java.sql.SQLException {
Long obj = new Long(x);
setObject(parameterIndex, obj, Types.BIGINT);
}
public void setFloat(int parameterIndex, float x) throws java.sql.SQLException {
Float obj = new Float(x);
setObject(parameterIndex, obj, Types.FLOAT);
}
public void setDouble(int parameterIndex, double x) throws java.sql.SQLException {
Double obj = new Double(x);
setObject(parameterIndex, obj, Types.DOUBLE);
}
public void setBigDecimal(int parameterIndex, BigDecimal x) throws java.sql.SQLException {
setObject(parameterIndex, x, Types.DECIMAL);
}
public void setString(int parameterIndex, String x) throws java.sql.SQLException {
setObject(parameterIndex, x, Types.VARCHAR);
}
public void setBytes(int parameterIndex, byte[] x) throws java.sql.SQLException {
setObject(parameterIndex, x, Types.VARBINARY);
}
public void setDate(int parameterIndex, Date x) throws java.sql.SQLException {
// ex. '1999-02-14'
setObject(parameterIndex, x, Types.DATE);
}
public void setTime(int parameterIndex, Time x) throws java.sql.SQLException {
// ex. '12:34:56'
setObject(parameterIndex, x, Types.TIME);
}
public void setTimestamp(int parameterIndex, Timestamp x) throws java.sql.SQLException {
// ex. '1999-02-14 12:34:56'
setObject(parameterIndex, x, Types.TIMESTAMP);
}
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws java.sql.SQLException {
throw new SQLException("mysql does not support setAsciiStream(int, InputStream, int).");
}
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws java.sql.SQLException {
throw new SQLException("mysql does not support setUnicodeStream(int, InputStream, int).");
}
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws java.sql.SQLException {
setObject(parameterIndex, new MyPreparedObject(x, length), Types.LONGVARBINARY);
}
public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws java.sql.SQLException {
setObject(parameterIndex, x, targetSqlType);
}
public void setObject(int parameterIndex, Object x, int targetSqlType) throws java.sql.SQLException {
if( param_obj_array != null &&
param_type_array != null )
{
if( parameterIndex <= param_obj_array.length &&
parameterIndex <= param_type_array.length )
{
param_obj_array[parameterIndex-1] = x;
if( (x instanceof byte[]) && (targetSqlType != Types.VARBINARY) )
targetSqlType = Types.VARBINARY;
if( (x instanceof InputStream) && (targetSqlType != Types.LONGVARBINARY) )
targetSqlType = Types.LONGVARBINARY;
param_type_array[parameterIndex-1] = targetSqlType;
return;
}
}
throw new SQLException("PreparedStatement Error : setObject(int, Object, int).");
}
public void setObject(int parameterIndex, Object x) throws java.sql.SQLException {
throw new SQLException("mysql does not support setObject(int, Object).");
}
// for JDBC2.0 java.sql.ResultSet
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
throw new SQLException("mysql does not support setCharacterStream(int, Reader, int).");
}
public void setRef(int i, Ref x) throws SQLException {
throw new SQLException("mysql does not support setRef(int, Ref).");
}
public void setBlob(int i, Blob x) throws SQLException {
setBinaryStream(i, x.getBinaryStream(), (int)x.length());
}
public void setClob(int i, Clob x) throws SQLException {
throw new SQLException("mysql does not support setClob(int, Clob).");
}
public void setArray(int i, Array x) throws SQLException {
throw new SQLException("mysql does not support setArray(int, Array).");
}
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
// ex. '1999-02-14'
setObject(parameterIndex, x, Types.DATE);
}
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
// ex. '12:34:56'
setObject(parameterIndex, x, Types.TIME);
}
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
// ex. '1999-02-14 12:34:56'
setObject(parameterIndex, x, Types.TIMESTAMP);
}
public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException {
throw new SQLException("mysql does not support setNull(int, int, String).");
}
// for JDBC2.0 java.sql.ResultSet
public boolean next() throws SQLException {
int row_count = rows.size();
if( index + 1 <= row_count )
{
index++;
notifyCursorMoved();
return true;
}
return false;
}
public void close() throws SQLException {
if( updater != null )
{
try { updater.close(); }
catch(Exception ex) { }
updater = null;
}
rows = null;
}
public boolean wasNull() throws SQLException {
return last_null;
}
public String getString(int columnIndex) throws SQLException {
Object retval = getObject(columnIndex);
if( retval instanceof java.lang.Character )
return retval != null ? String.valueOf((int)((java.lang.Character)retval).charValue()) : null;
else
return retval != null ? retval.toString() : null;
}
public boolean getBoolean(int columnIndex) throws SQLException {
String s = getString(columnIndex);
try {
return Boolean.valueOf(s).booleanValue();
}
catch(Exception e) {
// throw new SQLException(e.getMessage());
return false;
}
}
public byte getByte(int columnIndex) throws SQLException {
String s = getString(columnIndex);
try {
return Byte.valueOf(s).byteValue();
}
catch(Exception e) {
// throw new SQLException(e.getMessage());
return 0;
}
}
public short getShort(int columnIndex) throws SQLException {
String s = getString(columnIndex);
try {
return Short.valueOf(s).shortValue();
}
catch(Exception e) {
// throw new SQLException(e.getMessage());
return 0;
}
}
public int getInt(int columnIndex) throws SQLException {
String s = getString(columnIndex);
try {
return Integer.valueOf(s).intValue();
}
catch(Exception e) {
// throw new SQLException(e.getMessage());
return 0;
}
}
public long getLong(int columnIndex) throws SQLException {
String s = getString(columnIndex);
try {
return Long.valueOf(s).longValue();
}
catch(Exception e) {
// throw new SQLException(e.getMessage());
return 0;
}
}
public float getFloat(int columnIndex) throws SQLException {
String s = getString(columnIndex);
try {
return Float.valueOf(s).floatValue();
}
catch(Exception e) {
// throw new SQLException(e.getMessage());
return 0.0f;
}
}
public double getDouble(int columnIndex) throws SQLException {
String s = getString(columnIndex);
try {
return Double.valueOf(s).doubleValue();
}
catch(Exception e) {
// throw new SQLException(e.getMessage());
return 0.0;
}
}
public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {
return (BigDecimal)getObject(columnIndex);
}
public byte[] getBytes(int columnIndex) throws SQLException {
return (byte[])getObject(columnIndex);
}
public Date getDate(int columnIndex) throws SQLException {
return (Date)getObject(columnIndex);
}
public Time getTime(int columnIndex) throws SQLException {
return (Time)getObject(columnIndex);
}
public Timestamp getTimestamp(int columnIndex) throws SQLException {
return (Timestamp)getObject(columnIndex);
}
public InputStream getAsciiStream(int columnIndex) throws SQLException {
throw new SQLException("mysql does not support getAsciiStream(int).");
}
public InputStream getUnicodeStream(int columnIndex) throws SQLException {
throw new SQLException("mysql does not support getUnicodeStream(int).");
}
public InputStream getBinaryStream(int columnIndex) throws SQLException {
byte[] bin_buf = getBytes(columnIndex);
if( bin_buf == null )
return null;
return new java.io.ByteArrayInputStream(bin_buf);
}
public String getString(String columnName) throws SQLException {
return getString(findColumn(columnName));
}
public boolean getBoolean(String columnName) throws SQLException {
return getBoolean(findColumn(columnName));
}
public byte getByte(String columnName) throws SQLException {
return getByte(findColumn(columnName));
}
public short getShort(String columnName) throws SQLException {
return getShort(findColumn(columnName));
}
public int getInt(String columnName) throws SQLException {
return getInt(findColumn(columnName));
}
public long getLong(String columnName) throws SQLException {
return getLong(findColumn(columnName));
}
public float getFloat(String columnName) throws SQLException {
return getFloat(findColumn(columnName));
}
public double getDouble(String columnName) throws SQLException {
return getDouble(findColumn(columnName));
}
public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException {
return getBigDecimal(findColumn(columnName));
}
public byte[] getBytes(String columnName) throws SQLException {
return getBytes(findColumn(columnName));
}
public Date getDate(String columnName) throws SQLException {
return getDate(findColumn(columnName));
}
public Time getTime(String columnName) throws SQLException {
return getTime(findColumn(columnName));
}
public Timestamp getTimestamp(String columnName) throws SQLException {
return getTimestamp(findColumn(columnName));
}
public InputStream getAsciiStream(String columnName) throws SQLException {
return getAsciiStream(findColumn(columnName));
}
public InputStream getUnicodeStream(String columnName) throws SQLException {
return getUnicodeStream(findColumn(columnName));
}
public InputStream getBinaryStream(String columnName) throws SQLException {
return getBinaryStream(findColumn(columnName));
}
public SQLWarning getWarnings() throws SQLException {
return null;
}
public void clearWarnings() throws SQLException {
}
public String getCursorName() throws SQLException {
return "";
}
public ResultSetMetaData getMetaData() throws SQLException {
return rs_meta;
}
public Object getObject(int columnIndex) throws SQLException {
try {
ArrayList rowdata = (ArrayList)rows.get(index-1);
Object data = rowdata.get(columnIndex-1);
last_null = data == null ? true : false;
return data;
}
catch(Exception e) {
return null;
}
}
public Object getObject(String columnName) throws SQLException {
return getObject(findColumn(columnName));
}
public int findColumn(String name) throws SQLException {
try {
Integer nI = (Integer) columnName.get(name);
if (nI==null) nI = (Integer) columnFullName.get(name);
if (nI!=null) return nI.intValue()+1;
throw new SQLException("Invalid column name : "+name);
}
catch( Exception e ) {
throw new SQLException(e.getMessage());
}
}
public Reader getCharacterStream(int columnIndex) throws SQLException {
return null;
}
public Reader getCharacterStream(String columnName) throws SQLException {
return getCharacterStream(findColumn(columnName));
}
public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
return getBigDecimal(columnIndex, 10);
}
public BigDecimal getBigDecimal(String columnName) throws SQLException {
return getBigDecimal(findColumn(columnName));
}
public boolean isBeforeFirst() throws SQLException {
int row_count = rows.size();
if( row_count > 0 && index == 0 )
{
return true;
}
return false;
}
public boolean isAfterLast() throws SQLException {
int row_count = rows.size();
if( row_count > 0 && index == row_count + 1 )
{
return true;
}
return false;
}
public boolean isFirst() throws SQLException {
int row_count = rows.size();
if( row_count > 0 && index == 1 )
{
return true;
}
return false;
}
public boolean isLast() throws SQLException {
int row_count = rows.size();
if( row_count > 0 && index == row_count )
{
return true;
}
return false;
}
public void beforeFirst() throws SQLException {
if( getType() == ResultSet.TYPE_FORWARD_ONLY )
throw new SQLException("TYPE_FORWARD_ONLY ResultSet does not support previous().");
int row_count = rows.size();
if( row_count > 0 )
{
index = 0;
notifyCursorMoved();
}
}
public void afterLast() throws SQLException {
if( getType() == ResultSet.TYPE_FORWARD_ONLY )
throw new SQLException("TYPE_FORWARD_ONLY ResultSet does not support previous().");
int row_count = rows.size();
if( row_count > 0 )
{
index = row_count + 1;
notifyCursorMoved();
}
}
public boolean first() throws SQLException {
if( getType() == ResultSet.TYPE_FORWARD_ONLY )
throw new SQLException("TYPE_FORWARD_ONLY ResultSet does not support previous().");
int row_count = rows.size();
if( row_count > 0 )
{
index = 1;
notifyCursorMoved();
return true;
}
return false;
}
public boolean last() throws SQLException {
if( getType() == ResultSet.TYPE_FORWARD_ONLY )
throw new SQLException("TYPE_FORWARD_ONLY ResultSet does not support previous().");
int row_count = rows.size();
if( row_count > 0 )
{
index = row_count;
notifyCursorMoved();
return true;
}
return false;
}
public int getRow() throws SQLException {
return index;
}
public boolean absolute(int row) throws SQLException {
if( getType() == ResultSet.TYPE_FORWARD_ONLY )
throw new SQLException("TYPE_FORWARD_ONLY ResultSet does not support previous().");
if( row == 0 )
return false;
int row_count = rows.size();
if( row < 0 )
row = row_count + 1 + row;
index = row;
if( index >= 1 && index <= row_count )
{
notifyCursorMoved();
return true;
}
if( index <= 0 )
beforeFirst();
else
afterLast();
return false;
}
public boolean relative(int row) throws SQLException {
if( getType() == ResultSet.TYPE_FORWARD_ONLY )
throw new SQLException("TYPE_FORWARD_ONLY ResultSet does not support previous().");
int row_count = rows.size();
index += row;
if( index >= 1 && index <= row_count )
{
notifyCursorMoved();
return true;
}
if( index <= 0 )
beforeFirst();
else
afterLast();
return false;
}
public boolean previous() throws SQLException {
if( getType() == ResultSet.TYPE_FORWARD_ONLY )
throw new SQLException("TYPE_FORWARD_ONLY ResultSet does not support previous().");
if( index - 1 >= 1 )
{
index--;
notifyCursorMoved();
return true;
}
return false;
}
public void setFetchDirection(int direction) throws SQLException {
fetchDirection = direction;
}
public int getFetchDirection() throws SQLException {
return fetchDirection;
}
public void setFetchSize(int rows) throws SQLException {
fetchSize = rows;
}
public int getFetchSize() throws SQLException {
return fetchSize;
}
public int getType() throws SQLException {
return resultSetType;
}
public int getConcurrency() throws SQLException {
return resultSetConcurrency;
}
public boolean rowUpdated() throws SQLException {
throw new SQLException("mysql does not support rowUpdated().");
}
public boolean rowInserted() throws SQLException {
throw new SQLException("mysql does not support rowInserted().");
}
public boolean rowDeleted() throws SQLException {
try {
ArrayList rowdata = (ArrayList)rows.get(index-1);
return rowdata == null;
}
catch(Exception e) {
throw new SQLException(e.getMessage());
}
}
public void updateNull(int columnIndex) throws SQLException {
this.updateObject(columnIndex, null);
}
public void updateBoolean(int columnIndex, boolean x) throws SQLException {
throw new SQLException("mysql does not support updateBoolean(int, boolean).");
}
public void updateByte(int columnIndex, byte x) throws SQLException {
Byte obj = new Byte(x);
this.updateObjectEx(columnIndex, obj, Types.TINYINT);
}
public void updateShort(int columnIndex, short x) throws SQLException {
Short obj = new Short(x);
this.updateObjectEx(columnIndex, obj, Types.SMALLINT);
}
public void updateInt(int columnIndex, int x) throws SQLException {
Integer obj = new Integer(x);
this.updateObjectEx(columnIndex, obj, Types.INTEGER);
}
public void updateLong(int columnIndex, long x) throws SQLException {
Long obj = new Long(x);
this.updateObjectEx(columnIndex, obj, Types.BIGINT);
}
public void updateFloat(int columnIndex, float x) throws SQLException {
Float obj = new Float(x);
this.updateObjectEx(columnIndex, obj, Types.FLOAT);
}
public void updateDouble(int columnIndex, double x) throws SQLException {
Double obj = new Double(x);
this.updateObjectEx(columnIndex, obj, Types.DOUBLE);
}
public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException {
this.updateObjectEx(columnIndex, x, Types.DECIMAL);
}
public void updateString(int columnIndex, String x) throws SQLException {
this.updateObjectEx(columnIndex, x, Types.VARCHAR);
}
public void updateBytes(int columnIndex, byte[] x) throws SQLException {
this.updateObjectEx(columnIndex, x, Types.VARBINARY);
}
public void updateDate(int columnIndex, Date x) throws SQLException {
this.updateObjectEx(columnIndex, x, Types.DATE);
}
public void updateTime(int columnIndex, Time x) throws SQLException {
this.updateObjectEx(columnIndex, x, Types.TIME);
}
public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException {
this.updateObjectEx(columnIndex, x, Types.TIMESTAMP);
}
public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException {
throw new SQLException("mysql does not support updateAsciiStream(int, InputStream, int).");
}
public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException {
this.updateObjectEx(columnIndex, new MyPreparedObject(x, length), Types.LONGVARBINARY);
}
public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException {
throw new SQLException("mysql does not support updateCharacterStream(int, Reader, int).");
}
public void updateObject(int columnIndex, Object x, int scale) throws SQLException {
this.updateObject(columnIndex, x);
}
public void updateObject(int columnIndex, Object x) throws SQLException {
ResultSetMetaData meta = this.getMetaData();
int targetSqlType = meta.getColumnType(columnIndex);
updateObjectEx(columnIndex, x, targetSqlType);
}
private void updateObjectEx(int columnIndex, Object x, int targetSqlType) throws SQLException {
if( getConcurrency() != ResultSet.CONCUR_UPDATABLE )
throw new SQLException("CONCUR_READ_ONLY RowSet does not support updateObject.");
if( update_obj_array != null &&
update_type_array != null )
{
if( columnIndex <= update_obj_array.length &&
columnIndex <= update_type_array.length )
{
update_obj_array[columnIndex-1] = x;
if( (x instanceof byte[]) && (targetSqlType != Types.VARBINARY) )
targetSqlType = Types.VARBINARY;
if( (x instanceof InputStream) && (targetSqlType != Types.LONGVARBINARY) )
targetSqlType = Types.LONGVARBINARY;
update_type_array[columnIndex-1] = targetSqlType;
return;
}
}
throw new SQLException("MyRowSet Error : updateObject(int, Object).");
}
public void updateNull(String columnName) throws SQLException {
updateNull(findColumn(columnName));
}
public void updateBoolean(String columnName, boolean x) throws SQLException {
throw new SQLException("mysql does not support updateBoolean(String, boolean).");
}
public void updateByte(String columnName, byte x) throws SQLException {
updateByte(findColumn(columnName), x);
}
public void updateShort(String columnName, short x) throws SQLException {
updateShort(findColumn(columnName), x);
}
public void updateInt(String columnName, int x) throws SQLException {
updateInt(findColumn(columnName), x);
}
public void updateLong(String columnName, long x) throws SQLException {
updateLong(findColumn(columnName), x);
}
public void updateFloat(String columnName, float x) throws SQLException {
updateFloat(findColumn(columnName), x);
}
public void updateDouble(String columnName, double x) throws SQLException {
updateDouble(findColumn(columnName), x);
}
public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException {
updateBigDecimal(findColumn(columnName), x);
}
public void updateString(String columnName, String x) throws SQLException {
updateString(findColumn(columnName), x);
}
public void updateBytes(String columnName, byte[] x) throws SQLException {
updateBytes(findColumn(columnName), x);
}
public void updateDate(String columnName, Date x) throws SQLException {
updateDate(findColumn(columnName), x);
}
public void updateTime(String columnName, Time x) throws SQLException {
updateTime(findColumn(columnName), x);
}
public void updateTimestamp(String columnName, Timestamp x) throws SQLException {
updateTimestamp(findColumn(columnName), x);
}
public void updateAsciiStream(String columnName, InputStream x, int length) throws SQLException {
throw new SQLException("mysql does not support updateAsciiStream(String, InputStream, int).");
}
public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException {
updateBinaryStream(findColumn(columnName), x, length);
}
public void updateCharacterStream(String columnName, Reader reader, int length) throws SQLException {
throw new SQLException("mysql does not support updateCharacterStream(String, Reader, int).");
}
public void updateObject(String columnName, Object x, int scale) throws SQLException {
updateObject(findColumn(columnName), x, scale);
}
public void updateObject(String columnName, Object x) throws SQLException {
updateObject(findColumn(columnName), x);
}
private Connection getConnectionForUpdate() throws java.sql.SQLException {
if( updater == null )
{
updater = getConnection();
if( transactionIsolation != MyRowSet.TRANSACTION_UNKNOWN )
updater.setTransactionIsolation(transactionIsolation);
updater.setReadOnly(readOnly);
updater.setTypeMap(typemap);
}
return updater;
}
public void insertRow() throws SQLException {
if( getConcurrency() != ResultSet.CONCUR_UPDATABLE )
throw new SQLException("CONCUR_READ_ONLY RowSet does not support insertRow.");
if( !onetable )
throw new SQLException("RowSet generated from Multiple Tables does not support insertRow.");
if( !insertmode )
throw new SQLException("insertRow() cannot be called when the cursor is not on the insert row.");
ResultSetMetaData meta = this.getMetaData();
StringBuffer updatesql = new StringBuffer();
updatesql.append("INSERT INTO ");
updatesql.append(meta.getTableName(1));
updatesql.append("(");
boolean first = true;
for(int i = 1; i <= update_obj_array.length; i++)
{
if( update_type_array[i-1] != Types.NULL )
{
if( first )
first = false;
else
updatesql.append(",");
updatesql.append(meta.getColumnName(i));
}
}
updatesql.append(")");
updatesql.append(" VALUES(");
first = true;
for(int i = 1; i <= update_obj_array.length; i++)
{
if( update_type_array[i-1] != Types.NULL )
{
if( first )
first = false;
else
updatesql.append(",");
updatesql.append("?");
}
}
updatesql.append(");");
Connection conn = getConnectionForUpdate();
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(updatesql.toString());
int param_index = 1;
for(int i = 1; i <= update_obj_array.length; i++)
{
int targetSqlType = update_type_array[i-1];
if( targetSqlType != Types.NULL )
{
stmt.setObject(param_index, update_obj_array[i-1], targetSqlType);
param_index++;
}
}
int count = stmt.executeUpdate();
if( count == 1 )
{
ArrayList vecrow = new ArrayList();
for(int i = 1; i <= update_obj_array.length; i++)
{
if( update_type_array[i-1] != Types.NULL )
vecrow.add(update_obj_array[i-1]);
else
vecrow.add(null);
}
rows.add(vecrow);
notifyRowChanged();
}
else
{
throw new SQLException("Can not insert Row.");
}
}
finally {
if( stmt != null )
{
try { stmt.close(); }
catch(Exception ex) { }
stmt = null;
}
}
}
public void updateRow() throws SQLException {
if( getConcurrency() != ResultSet.CONCUR_UPDATABLE )
throw new SQLException("CONCUR_READ_ONLY RowSet does not support updateRow.");
if( !onetable )
throw new SQLException("RowSet generated from Multiple Tables does not support updateRow.");
if( insertmode )
throw new SQLException("updateRow() cannot be called when the cursor is on the insert row.");
ResultSetMetaData meta = this.getMetaData();
StringBuffer updatesql = new StringBuffer();
updatesql.append("UPDATE ");
updatesql.append(meta.getTableName(1));
updatesql.append(" SET ");
boolean first = true;
for(int i = 1; i <= update_obj_array.length; i++)
{
if( update_type_array[i-1] != Types.NULL )
{
if( first )
first = false;
else
updatesql.append(",");
updatesql.append(meta.getColumnName(i));
updatesql.append("=?");
}
}
updatesql.append(" WHERE ");
for(int i = 0; i < pk_cols.size(); i++)
{
if( i != 0 )
updatesql.append(" AND ");
String pkname = (String)pk_cols.elementAt(i);
updatesql.append(pkname);
updatesql.append("=?");
}
updatesql.append(";");
Connection conn = getConnectionForUpdate();
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(updatesql.toString());
int param_index = 1;
for(int i = 1; i <= update_obj_array.length; i++)
{
int targetSqlType = update_type_array[i-1];
if( targetSqlType != Types.NULL )
{
stmt.setObject(param_index, update_obj_array[i-1], targetSqlType);
param_index++;
}
}
for(int i = 0; i < pk_cols.size(); i++)
{
String pkname = (String)pk_cols.elementAt(i);
int targetSqlType = meta.getColumnType(findColumn(pkname));
stmt.setObject(param_index, getObject(pkname), targetSqlType);
param_index++;
}
int count = stmt.executeUpdate();
if( count == 1 )
{
ArrayList rowdata = (ArrayList)rows.get(index-1);
for(int i = 1; i <= update_obj_array.length; i++)
{
if( update_type_array[i-1] != Types.NULL )
rowdata.set(i-1, update_obj_array[i-1]);
}
notifyRowChanged();
}
}
finally {
if( stmt != null )
{
try { stmt.close(); }
catch(Exception ex) { }
stmt = null;
}
}
}
public void deleteRow() throws SQLException {
if( getConcurrency() != ResultSet.CONCUR_UPDATABLE )
throw new SQLException("CONCUR_READ_ONLY RowSet does not support deleteRow.");
if( !onetable )
throw new SQLException("RowSet generated from Multiple Tables does not support deleteRow.");
if( insertmode )
throw new SQLException("deleteRow() cannot be called when the cursor is on the insert row.");
ResultSetMetaData meta = this.getMetaData();
StringBuffer updatesql = new StringBuffer();
updatesql.append("DELETE FROM ");
updatesql.append(meta.getTableName(1));
updatesql.append(" WHERE ");
for(int i = 0; i < pk_cols.size(); i++)
{
if( i != 0 )
updatesql.append(" AND ");
String pkname = (String)pk_cols.elementAt(i);
updatesql.append(pkname);
updatesql.append("=?");
}
updatesql.append(";");
Connection conn = getConnectionForUpdate();
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(updatesql.toString());
int param_index = 1;
for(int i = 0; i < pk_cols.size(); i++)
{
String pkname = (String)pk_cols.elementAt(i);
int targetSqlType = meta.getColumnType(findColumn(pkname));
stmt.setObject(param_index, getObject(pkname), targetSqlType);
param_index++;
}
int count = stmt.executeUpdate();
if( count == 1 )
{
rows.set(index-1, null);
notifyRowChanged();
}
else
{
throw new SQLException("Can not delete Row.");
}
}
finally {
if( stmt != null )
{
try { stmt.close(); }
catch(Exception ex) { }
stmt = null;
}
}
}
public void refreshRow() throws SQLException {
if( getConcurrency() != ResultSet.CONCUR_UPDATABLE )
throw new SQLException("CONCUR_READ_ONLY RowSet does not support refreshRow.");
if( !onetable )
throw new SQLException("RowSet generated from Multiple Tables does not support refreshRow.");
if( insertmode )
throw new SQLException("refreshRow() cannot be called when the cursor is on the insert row.");
if( rowDeleted() )
return;
ResultSetMetaData meta = this.getMetaData();
StringBuffer updatesql = new StringBuffer();
updatesql.append("SELECT ");
int colnum = meta.getColumnCount();
for(int i = 1; i <= colnum; i++)
{
if( i != 1 )
updatesql.append(",");
updatesql.append(meta.getColumnName(i));
}
updatesql.append(" FROM ");
updatesql.append(meta.getTableName(1));
updatesql.append(" WHERE ");
for(int i = 0; i < pk_cols.size(); i++)
{
if( i != 0 )
updatesql.append(" AND ");
String pkname = (String)pk_cols.elementAt(i);
updatesql.append(pkname);
updatesql.append("=?");
}
updatesql.append(";");
Connection conn = getConnectionForUpdate();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement(updatesql.toString());
int param_index = 1;
for(int i = 0; i < pk_cols.size(); i++)
{
String pkname = (String)pk_cols.elementAt(i);
int targetSqlType = meta.getColumnType(findColumn(pkname));
stmt.setObject(param_index, getObject(pkname), targetSqlType);
param_index++;
}
rs = stmt.executeQuery();
if( rs.next() )
{
ArrayList rowdata = (ArrayList)rows.get(index-1);
for(int i = 1; i <= colnum; i++)
rowdata.set(i-1, rs.getObject(i));
}
else
{
throw new SQLException("Can not refresh Row.");
}
}
finally {
if( rs != null )
{
try { rs.close(); }
catch(Exception ex) { }
rs = null;
}
if( stmt != null )
{
try { stmt.close(); }
catch(Exception ex) { }
stmt = null;
}
clearUpdaters();
}
}
private void clearUpdaters() {
if( update_obj_array != null &&
update_type_array != null )
{
int i;
for(i = 0; i < update_obj_array.length; i++)
update_obj_array[i] = null;
for(i = 0; i < update_type_array.length; i++)
update_type_array[i] = Types.NULL;
}
}
public void cancelRowUpdates() throws SQLException {
if( getConcurrency() != ResultSet.CONCUR_UPDATABLE )
throw new SQLException("CONCUR_READ_ONLY RowSet does not support cancelRowUpdates.");
clearUpdaters();
}
public void moveToInsertRow() throws SQLException {
if( getConcurrency() != ResultSet.CONCUR_UPDATABLE )
throw new SQLException("CONCUR_READ_ONLY RowSet does not support moveToInsertRow.");
if( !onetable )
throw new SQLException("RowSet generated from Multiple Tables does not support moveToInsertRow.");
insertmode = true;
clearUpdaters();
}
public void moveToCurrentRow() throws SQLException {
if( getConcurrency() != ResultSet.CONCUR_UPDATABLE )
throw new SQLException("CONCUR_READ_ONLY RowSet does not support moveToCurrentRow.");
insertmode = false;
clearUpdaters();
}
public Statement getStatement() throws SQLException {
return new MyRowSetStatement(getConnectionForUpdate());
}
public Object getObject(int i, Map map) throws SQLException {
throw new SQLException("mysql does not support getObject(int, Map).");
}
public Ref getRef(int i) throws SQLException {
throw new SQLException("mysql does not support getRef(int).");
}
public Blob getBlob(int i) throws SQLException {
throw new SQLException("mysql does not support getBlob(int).");
}
public Clob getClob(int i) throws SQLException {
throw new SQLException("mysql does not support getClob(int).");
}
public Array getArray(int i) throws SQLException {
throw new SQLException("mysql does not support getArray(int).");
}
public Object getObject(String colName, Map map) throws SQLException {
throw new SQLException("mysql does not support getObject(String, Map).");
}
public Ref getRef(String colName) throws SQLException {
throw new SQLException("mysql does not support getRef(String).");
}
public Blob getBlob(String colName) throws SQLException {
throw new SQLException("mysql does not support getBlob(String).");
}
public Clob getClob(String colName) throws SQLException {
throw new SQLException("mysql does not support getClob(String).");
}
public Array getArray(String colName) throws SQLException {
throw new SQLException("mysql does not support getArray(String).");
}
public Date getDate(int columnIndex, Calendar cal) throws SQLException {
return getDate(columnIndex);
}
public Date getDate(String columnName, Calendar cal) throws SQLException {
return getDate(findColumn(columnName));
}
public Time getTime(int columnIndex, Calendar cal) throws SQLException {
return getTime(columnIndex);
}
public Time getTime(String columnName, Calendar cal) throws SQLException {
return getTime(findColumn(columnName));
}
public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException {
return getTimestamp(columnIndex);
}
public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException {
return getTimestamp(findColumn(columnName));
}
private void notifyCursorMoved() {
if( !listeners.isEmpty() )
{
RowSetEvent rowsetevent = new RowSetEvent((RowSet)this);
Iterator iterator = listeners.iterator();
while( iterator.hasNext() )
{
((RowSetListener)iterator.next()).cursorMoved(rowsetevent);
}
}
}
private void notifyRowChanged() {
if( !listeners.isEmpty() )
{
RowSetEvent rowsetevent = new RowSetEvent((RowSet)this);
Iterator iterator = listeners.iterator();
while( iterator.hasNext() )
{
((RowSetListener)iterator.next()).rowChanged(rowsetevent);
}
}
}
private void notifyRowSetChanged() {
if( !listeners.isEmpty() )
{
RowSetEvent rowsetevent = new RowSetEvent((RowSet)this);
Iterator iterator = listeners.iterator();
while( iterator.hasNext() )
{
((RowSetListener)iterator.next()).rowSetChanged(rowsetevent);
}
}
}
// for Serialization
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
}
}
class MyPreparedObject {
private int length;
private Object obj;
public MyPreparedObject(Object x, int len) {
length = len;
obj = x;
}
public int getLength() {
return length;
}
public Object getObj() {
return obj;
}
}
class MyRowSetStatement implements Statement {
private Connection connection = null;
MyRowSetStatement(Connection connection) {
this.connection = connection;
}
public Connection getConnection() throws SQLException {
return connection;
}
public ResultSet executeQuery(String sql) throws SQLException {
throw new java.lang.UnsupportedOperationException("method executeQuery() is not implemented.");
}
public int executeUpdate(String sql) throws SQLException {
throw new java.lang.UnsupportedOperationException("method executeUpdate() is not implemented.");
}
public void close() throws SQLException {
throw new java.lang.UnsupportedOperationException("method close() is not implemented.");
}
public int getMaxFieldSize() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getMaxFieldSize() is not implemented.");
}
public void setMaxFieldSize(int max) throws SQLException {
throw new java.lang.UnsupportedOperationException("method setMaxFieldSize() is not implemented.");
}
public int getMaxRows() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getMaxRows() is not implemented.");
}
public void setMaxRows(int max) throws SQLException {
throw new java.lang.UnsupportedOperationException("method setMaxRows() is not implemented.");
}
public void setEscapeProcessing(boolean enable) throws SQLException {
throw new java.lang.UnsupportedOperationException("method setEscapeProcessing() is not implemented.");
}
public int getQueryTimeout() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getQueryTimeout() is not implemented.");
}
public void setQueryTimeout(int seconds) throws SQLException {
throw new java.lang.UnsupportedOperationException("method setQueryTimeout() is not implemented.");
}
public void cancel() throws SQLException {
throw new java.lang.UnsupportedOperationException("method cancel() is not implemented.");
}
public SQLWarning getWarnings() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getWarnings() is not implemented.");
}
public void clearWarnings() throws SQLException {
throw new java.lang.UnsupportedOperationException("method clearWarnings() is not implemented.");
}
public void setCursorName(String name) throws SQLException {
throw new java.lang.UnsupportedOperationException("method setCursorName() is not implemented.");
}
public boolean execute(String sql) throws SQLException {
throw new java.lang.UnsupportedOperationException("method execute() is not implemented.");
}
public ResultSet getResultSet() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getResultSet() is not implemented.");
}
public int getUpdateCount() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getUpdateCount() is not implemented.");
}
public boolean getMoreResults() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getMoreResults() is not implemented.");
}
public void setFetchDirection(int direction) throws SQLException {
throw new java.lang.UnsupportedOperationException("method setFetchDirection() is not implemented.");
}
public int getFetchDirection() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getFetchDirection() is not implemented.");
}
public void setFetchSize(int rows) throws SQLException {
throw new java.lang.UnsupportedOperationException("method setFetchSize() is not implemented.");
}
public int getFetchSize() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getFetchSize() is not implemented.");
}
public int getResultSetConcurrency() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getResultSetConcurrency() is not implemented.");
}
public int getResultSetType() throws SQLException {
throw new java.lang.UnsupportedOperationException("method getResultSetType() is not implemented.");
}
public void addBatch(String sql) throws SQLException {
throw new java.lang.UnsupportedOperationException("method addBatch() is not implemented.");
}
public void clearBatch() throws SQLException {
throw new java.lang.UnsupportedOperationException("method clearBatch() is not implemented.");
}
public int[] executeBatch() throws SQLException {
throw new java.lang.UnsupportedOperationException("method executeBatch() is not implemented.");
}
}
----------------------------------------------------------------------------------------------------------------
--
高橋智宏
Java読書会( http://www.javareading.com/bof/ )