1 21 22 package org.dbunit.database; 23 24 import org.dbunit.database.statement.IStatementFactory; 25 import org.dbunit.dataset.*; 26 import org.dbunit.dataset.datatype.IDataTypeFactory; 27 28 import java.sql.ResultSet ; 29 import java.sql.SQLException ; 30 import java.sql.Statement ; 31 32 37 public abstract class AbstractDatabaseConnection implements IDatabaseConnection 38 { 39 private IDataSet _dataSet = null; 40 private DatabaseConfig _databaseConfig; 41 42 public AbstractDatabaseConnection() 43 { 44 _databaseConfig = new DatabaseConfig(); 45 } 46 47 50 public IDataSet createDataSet() throws SQLException 51 { 52 if (_dataSet == null) 53 { 54 _dataSet = new DatabaseDataSet(this); 55 } 56 57 return _dataSet; 58 } 59 60 public IDataSet createDataSet(String [] tableNames) throws SQLException 61 { 62 return new FilteredDataSet(tableNames, createDataSet()); 63 } 64 65 public ITable createQueryTable(String resultName, String sql) 66 throws DataSetException, SQLException 67 { 68 Statement statement = getConnection().createStatement(); 69 try 70 { 71 ResultSet resultSet = statement.executeQuery(sql); 72 73 try 74 { 75 IDataTypeFactory typeFactory = (IDataTypeFactory)_databaseConfig.getProperty( 76 DatabaseConfig.PROPERTY_DATATYPE_FACTORY); 77 ITableMetaData metaData = DatabaseTableMetaData.createMetaData( 78 resultName, resultSet, typeFactory); 79 return new CachedResultSetTable(metaData, resultSet); 80 } 81 finally 82 { 83 resultSet.close(); 84 } 85 } 86 finally 87 { 88 statement.close(); 89 } 90 } 91 92 public int getRowCount(String tableName) throws SQLException 93 { 94 return getRowCount(tableName, null); 95 } 96 97 public int getRowCount(String tableName, String whereClause) throws SQLException 98 { 99 StringBuffer sqlBuffer = new StringBuffer (128); 100 sqlBuffer.append("select count(*) from "); 101 sqlBuffer.append(tableName); 102 if (whereClause != null) 103 { 104 sqlBuffer.append(" "); 105 sqlBuffer.append(whereClause); 106 } 107 108 Statement statement = getConnection().createStatement(); 109 try 110 { 111 ResultSet resultSet = statement.executeQuery(sqlBuffer.toString()); 112 try 113 { 114 resultSet.next(); 115 return resultSet.getInt(1); 116 } 117 finally 118 { 119 resultSet.close(); 120 } 121 } 122 finally 123 { 124 statement.close(); 125 } 126 } 127 128 public DatabaseConfig getConfig() 129 { 130 return _databaseConfig; 131 } 132 133 public IStatementFactory getStatementFactory() 134 { 135 return (IStatementFactory)_databaseConfig.getProperty( 136 DatabaseConfig.PROPERTY_STATEMENT_FACTORY); 137 } 138 139 } 140 141 142 143 144 145 146 147 148 149 | Popular Tags |