diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e909a89d..0fe6a5717 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,20 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) +## [6.3.4] Preview Release +### Added +- Added new ThreadGroup creation to prevent IllegalThreadStateException if the underlying ThreadGroup has been destroyed. [#474](https://github.com/Microsoft/mssql-jdbc/pull/474) +- Added try-with-resources to JUnit tests [#520](https://github.com/Microsoft/mssql-jdbc/pull/520) + +### Fixed Issues +- Fixed the issue with passing parameters names that start with '@' to a CallableStatement [#495](https://github.com/Microsoft/mssql-jdbc/pull/495) +- Fixed SQLServerDataTable creation being O(n^2) issue [#514](https://github.com/Microsoft/mssql-jdbc/pull/514) + +### Changed +- Changed some manual array copying to System.arraycopy() [#500](https://github.com/Microsoft/mssql-jdbc/pull/500) +- Removed redundant toString() on String objects [#501](https://github.com/Microsoft/mssql-jdbc/pull/501) +- Replaced literals with constants [#502](https://github.com/Microsoft/mssql-jdbc/pull/502) + ## [6.3.3] Preview Release ### Added - Added connection properties for specifying custom TrustManager [#74](https://github.com/Microsoft/mssql-jdbc/pull/74) diff --git a/README.md b/README.md index 2196f02d4..1edeca9e1 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ To get the latest preview version of the driver, add the following to your POM f com.microsoft.sqlserver mssql-jdbc - 6.3.3.jre8-preview + 6.3.4.jre8-preview ``` @@ -120,7 +120,7 @@ Projects that require either of the two features need to explicitly declare the com.microsoft.sqlserver mssql-jdbc - 6.3.3.jre8-preview + 6.3.4.jre8-preview compile diff --git a/pom.xml b/pom.xml index 296eb209e..8c39911c9 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.microsoft.sqlserver mssql-jdbc - 6.3.4-SNAPSHOT + 6.3.4 jar diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java index 6bf3af9e6..77891c37b 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/DDC.java @@ -439,9 +439,7 @@ private static byte[] convertToBytes(BigDecimal value, } } int offset = numBytes - unscaledBytes.length; - for (int i = offset; i < numBytes; ++i) { - ret[i] = unscaledBytes[i - offset]; - } + System.arraycopy(unscaledBytes, offset - offset, ret, offset, numBytes - offset); return ret; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java index 4369d3c00..d87a9cb14 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/IOBuffer.java @@ -64,6 +64,7 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; @@ -498,7 +499,7 @@ class GregorianChange { GregorianCalendar cal = new GregorianCalendar(Locale.US); cal.clear(); - cal.set(1, 1, 577738, 0, 0, 0);// 577738 = 1+577737(no of days since epoch that brings us to oct 15th 1582) + cal.set(1, Calendar.FEBRUARY, 577738, 0, 0, 0);// 577738 = 1+577737(no of days since epoch that brings us to oct 15th 1582) if (cal.get(Calendar.DAY_OF_MONTH) == 15) { // If the date calculation is correct(the above bug is fixed), // post the default gregorian cut over date, the pure gregorian date @@ -4828,7 +4829,7 @@ private void writeInternalTVPRowValues(JDBCType jdbcType, else { if (isSqlVariant) { writeTVPSqlVariantHeader(10, TDSType.FLOAT8.byteValue(), (byte) 0); - writeDouble(Double.valueOf(currentColumnStringValue.toString())); + writeDouble(Double.valueOf(currentColumnStringValue)); break; } writeByte((byte) 8); // len of data bytes @@ -7119,13 +7120,21 @@ final class TimeoutTimer implements Runnable { private volatile Future task; private static final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { - private final ThreadGroup tg = new ThreadGroup(threadGroupName); - private final String threadNamePrefix = tg.getName() + "-"; + private final AtomicReference tgr = new AtomicReference<>(); private final AtomicInteger threadNumber = new AtomicInteger(0); @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(tg, r, threadNamePrefix + threadNumber.incrementAndGet()); + public Thread newThread(Runnable r) + { + ThreadGroup tg = tgr.get(); + + if (tg == null || tg.isDestroyed()) + { + tg = new ThreadGroup(threadGroupName); + tgr.set(tg); + } + + Thread t = new Thread(tg, r, tg.getName() + "-" + threadNumber.incrementAndGet()); t.setDaemon(true); return t; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java index 9c9f7b691..2aa091ff0 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLJdbcVersion.java @@ -11,6 +11,6 @@ final class SQLJdbcVersion { static final int major = 6; static final int minor = 3; - static final int patch = 3; + static final int patch = 4; static final int build = 0; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java index 14e4338b3..a383e1946 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy.java @@ -1521,7 +1521,7 @@ private String createInsertBulkCommand(TDSWriter tdsWriter) throws SQLServerExce if (it.hasNext()) { bulkCmd.append(" with ("); while (it.hasNext()) { - bulkCmd.append(it.next().toString()); + bulkCmd.append(it.next()); if (it.hasNext()) { bulkCmd.append(", "); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java index ec44c1834..ea9ff510f 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerBulkCopy42Helper.java @@ -75,7 +75,7 @@ static Object getTemporalObjectFromCSVWithFormatter(String valueStrUntrimmed, return ts; case java.sql.Types.TIME: // Time is returned as Timestamp to preserve nano seconds. - cal.set(connection.baseYear(), 00, 01); + cal.set(connection.baseYear(), Calendar.JANUARY, 01); ts = new java.sql.Timestamp(cal.getTimeInMillis()); ts.setNanos(taNano); return new java.sql.Timestamp(ts.getTime()); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java index 40a77be15..5ad8689c8 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerCallableStatement.java @@ -1451,6 +1451,15 @@ public NClob getNClob(String parameterName) throws SQLException { if (paramNames != null) l = paramNames.size(); + // handle `@name` as well as `name`, since `@name` is what's returned + // by DatabaseMetaData#getProcedureColumns + String columnNameWithoutAtSign = null; + if (columnName.startsWith("@")) { + columnNameWithoutAtSign = columnName.substring(1, columnName.length()); + } else { + columnNameWithoutAtSign = columnName; + } + // In order to be as accurate as possible when locating parameter name // indexes, as well as be deterministic when running on various client // locales, we search for parameter names using the following scheme: @@ -1465,7 +1474,7 @@ public NClob getNClob(String parameterName) throws SQLException { for (i = 0; i < l; i++) { String sParam = paramNames.get(i); sParam = sParam.substring(1, sParam.length()); - if (sParam.equals(columnName)) { + if (sParam.equals(columnNameWithoutAtSign)) { matchPos = i; break; } @@ -1477,7 +1486,7 @@ public NClob getNClob(String parameterName) throws SQLException { for (i = 0; i < l; i++) { String sParam = paramNames.get(i); sParam = sParam.substring(1, sParam.length()); - if (sParam.equalsIgnoreCase(columnName)) { + if (sParam.equalsIgnoreCase(columnNameWithoutAtSign)) { matchPos = i; break; } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java index 730f13bf7..a8397b605 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerConnection.java @@ -1717,7 +1717,7 @@ else if (0 == requestedPacketSize) sPropKey = SQLServerDriverStringProperty.SSL_PROTOCOL.toString(); sPropValue = activeConnectionProperties.getProperty(sPropKey); if (null == sPropValue) { - sPropValue = SQLServerDriverStringProperty.SSL_PROTOCOL.getDefaultValue().toString(); + sPropValue = SQLServerDriverStringProperty.SSL_PROTOCOL.getDefaultValue(); activeConnectionProperties.setProperty(sPropKey, sPropValue); } else { @@ -5430,7 +5430,7 @@ String getInstancePort(String server, browserResult = new String(receiveBuffer, 3, receiveBuffer.length - 3); if (connectionlogger.isLoggable(Level.FINER)) connectionlogger.fine( - toString() + " Received SSRP UDP response from IP address: " + udpResponse.getAddress().getHostAddress().toString()); + toString() + " Received SSRP UDP response from IP address: " + udpResponse.getAddress().getHostAddress()); } catch (IOException ioException) { // Warn and retry diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java index d3f176a31..60188841a 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerDataTable.java @@ -13,10 +13,12 @@ import java.time.OffsetDateTime; import java.time.OffsetTime; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.UUID; public final class SQLServerDataTable { @@ -24,6 +26,7 @@ public final class SQLServerDataTable { int rowCount = 0; int columnCount = 0; Map columnMetadata = null; + Set columnNames = null; Map rows = null; private String tvpName = null; @@ -37,6 +40,7 @@ public final class SQLServerDataTable { // Name used in CREATE TYPE public SQLServerDataTable() throws SQLServerException { columnMetadata = new LinkedHashMap<>(); + columnNames = new HashSet<>(); rows = new HashMap<>(); } @@ -75,7 +79,7 @@ public synchronized Iterator> getIterator() { public synchronized void addColumnMetadata(String columnName, int sqlType) throws SQLServerException { // column names must be unique - Util.checkDuplicateColumnName(columnName, columnMetadata); + Util.checkDuplicateColumnName(columnName, columnNames); columnMetadata.put(columnCount++, new SQLServerDataColumn(columnName, sqlType)); } @@ -89,10 +93,11 @@ public synchronized void addColumnMetadata(String columnName, */ public synchronized void addColumnMetadata(SQLServerDataColumn column) throws SQLServerException { // column names must be unique - Util.checkDuplicateColumnName(column.columnName, columnMetadata); + Util.checkDuplicateColumnName(column.columnName, columnNames); columnMetadata.put(columnCount++, column); } + /** * Adds one row of data to the data table. * diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java index 1d11e61af..dca580ec9 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerParameterMetaData.java @@ -793,7 +793,7 @@ public T unwrap(Class iface) throws SQLException { } catch (SQLException e) { SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return 0; + return parameterModeUnknown; } } @@ -913,7 +913,7 @@ public T unwrap(Class iface) throws SQLException { } catch (SQLException e) { SQLServerException.makeFromDriverError(con, stmtParent, e.toString(), null, false); - return 0; + return parameterNoNulls; } } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java index 1ba3c62e8..2437a82d0 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerPreparedStatement.java @@ -2503,8 +2503,7 @@ public long[] executeLargeBatch() throws SQLServerException, BatchUpdateExceptio updateCounts = new long[batchCommand.updateCounts.length]; - for (int i = 0; i < batchCommand.updateCounts.length; ++i) - updateCounts[i] = batchCommand.updateCounts[i]; + System.arraycopy(batchCommand.updateCounts, 0, updateCounts, 0, batchCommand.updateCounts.length); // Transform the SQLException into a BatchUpdateException with the update counts. if (null != batchCommand.batchException) { @@ -2571,8 +2570,7 @@ final void doExecutePreparedStatementBatch(PrepStmtBatchExecCmd batchCommand) th // Fill in the parameter values for this batch Parameter paramValues[] = batchParamValues.get(numBatchesPrepared); assert paramValues.length == batchParam.length; - for (int i = 0; i < paramValues.length; i++) - batchParam[i] = paramValues[i]; + System.arraycopy(paramValues, 0, batchParam, 0, paramValues.length); boolean hasExistingTypeDefinitions = preparedTypeDefinitions != null; boolean hasNewTypeDefinitions = buildPreparedStrings(batchParam, false); diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java index 6f68d685a..fa3d07dd6 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/TVP.java @@ -12,10 +12,12 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.MessageFormat; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; enum TVPType { ResultSet, @@ -48,6 +50,7 @@ class TVP { Iterator> sourceDataTableRowIterator = null; ISQLServerDataRecord sourceRecord = null; TVPType tvpType = null; + Set columnNames = null; // MultiPartIdentifierState enum MPIState { @@ -94,6 +97,7 @@ void initTVP(TVPType type, ISQLServerDataRecord tvpRecord) throws SQLServerException { initTVP(TVPType.ISQLServerDataRecord, tvpPartName); sourceRecord = tvpRecord; + columnNames = new HashSet<>(); // Populate TVP metdata from ISQLServerDataRecord. populateMetadataFromDataRecord(); @@ -185,8 +189,9 @@ void populateMetadataFromDataRecord() throws SQLServerException { throw new SQLServerException(SQLServerException.getErrString("R_TVPEmptyMetadata"), null); } for (int i = 0; i < sourceRecord.getColumnCount(); i++) { + Util.checkDuplicateColumnName(sourceRecord.getColumnMetaData(i + 1).columnName, columnNames); + // Make a copy here as we do not want to change user's metadata. - Util.checkDuplicateColumnName(sourceRecord.getColumnMetaData(i + 1).columnName, columnMetadata); SQLServerMetaData metaData = new SQLServerMetaData(sourceRecord.getColumnMetaData(i + 1)); columnMetadata.put(i, metaData); } diff --git a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java index db10ebce1..c1d6d81dc 100644 --- a/src/main/java/com/microsoft/sqlserver/jdbc/Util.java +++ b/src/main/java/com/microsoft/sqlserver/jdbc/Util.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; +import java.util.Set; import java.util.UUID; import java.util.logging.Level; import java.util.logging.LogManager; @@ -557,28 +558,22 @@ static String escapeSQLId(String inID) { outID.append(']'); return outID.toString(); } - + + /** + * Checks if duplicate columns exists, in O(n) time. + * + * @param columnName + * the name of the column + * @throws SQLServerException + * when a duplicate column exists + */ static void checkDuplicateColumnName(String columnName, - Map columnMetadata) throws SQLServerException { - if (columnMetadata.get(0) instanceof SQLServerMetaData) { - for (Entry entry : columnMetadata.entrySet()) { - SQLServerMetaData value = (SQLServerMetaData) entry.getValue(); - if (value.columnName.equals(columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } - } - } - else if (columnMetadata.get(0) instanceof SQLServerDataColumn) { - for (Entry entry : columnMetadata.entrySet()) { - SQLServerDataColumn value = (SQLServerDataColumn) entry.getValue(); - if (value.columnName.equals(columnName)) { - MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); - Object[] msgArgs = {columnName}; - throw new SQLServerException(null, form.format(msgArgs), null, 0, false); - } - } + Set columnNames) throws SQLServerException { + //columnList.add will return false if the same column name already exists + if (!columnNames.add(columnName)) { + MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_TVPDuplicateColumnName")); + Object[] msgArgs = {columnName}; + throw new SQLServerException(null, form.format(msgArgs), null, 0, false); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java index 6fc795a98..9ae2445c1 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/AESetup.java @@ -80,8 +80,6 @@ public class AESetup extends AbstractTest { static SQLServerColumnEncryptionKeyStoreProvider storeProvider = null; static SQLServerStatementColumnEncryptionSetting stmtColEncSetting = null; - private static SQLServerPreparedStatement pstmt = null; - /** * Create connection, statement and generate path of resource file * @@ -94,26 +92,28 @@ static void setUpConnection() throws TestAbortedException, Exception { "Aborting test case as SQL Server version is not compatible with Always encrypted "); String AETestConenctionString = connectionString + ";sendTimeAsDateTime=false"; - readFromFile(javaKeyStoreInputFile, "Alias name"); - con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString); - stmt = (SQLServerStatement) con.createStatement(); - dropCEK(); - dropCMK(); - con.close(); - + + try(SQLServerConnection con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString); + SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) { + dropCEK(stmt); + dropCMK(stmt); + } + keyPath = Utils.getCurrentClassPath() + jksName; storeProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider(keyPath, secretstrJks.toCharArray()); stmtColEncSetting = SQLServerStatementColumnEncryptionSetting.Enabled; + Properties info = new Properties(); info.setProperty("ColumnEncryptionSetting", "Enabled"); info.setProperty("keyStoreAuthentication", "JavaKeyStorePassword"); info.setProperty("keyStoreLocation", keyPath); info.setProperty("keyStoreSecret", secretstrJks); + con = (SQLServerConnection) DriverManager.getConnection(AETestConenctionString, info); stmt = (SQLServerStatement) con.createStatement(); createCMK(keyStoreName, javaKeyAliases); - createCEK(storeProvider); + createCEK(storeProvider); } /** @@ -126,8 +126,8 @@ static void setUpConnection() throws TestAbortedException, Exception { @AfterAll private static void dropAll() throws SQLServerException, SQLException { dropTables(stmt); - dropCEK(); - dropCMK(); + dropCEK(stmt); + dropCMK(stmt); Util.close(null, stmt, con); } @@ -140,33 +140,26 @@ private static void dropAll() throws SQLServerException, SQLException { */ private static void readFromFile(String inputFile, String lookupValue) throws IOException { - BufferedReader buffer = null; filePath = Utils.getCurrentClassPath(); try { File f = new File(filePath + inputFile); assumeTrue(f.exists(), "Aborting test case since no java key store and alias name exists!"); - buffer = new BufferedReader(new FileReader(f)); - String readLine = ""; - String[] linecontents; - - while ((readLine = buffer.readLine()) != null) { - if (readLine.trim().contains(lookupValue)) { - linecontents = readLine.split(" "); - javaKeyAliases = linecontents[2]; - break; - } + try(BufferedReader buffer = new BufferedReader(new FileReader(f))) { + String readLine = ""; + String[] linecontents; + + while ((readLine = buffer.readLine()) != null) { + if (readLine.trim().contains(lookupValue)) { + linecontents = readLine.split(" "); + javaKeyAliases = linecontents[2]; + break; + } + } } - } catch (IOException e) { fail(e.toString()); } - finally { - if (null != buffer) { - buffer.close(); - } - } - } /** @@ -744,60 +737,60 @@ protected static void dropTables(SQLServerStatement statement) throws SQLExcepti protected static void populateBinaryNormalCase(LinkedList byteValues) throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary20 - for (int i = 1; i <= 3; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(0)); - } - } - - // varbinary50 - for (int i = 4; i <= 6; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(1)); - } - } - - // varbinary(max) - for (int i = 7; i <= 9; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(2)); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary20 + for (int i = 1; i <= 3; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(0)); + } + } + + // varbinary50 + for (int i = 4; i <= 6; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(1)); + } + } + + // varbinary(max) + for (int i = 7; i <= 9; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(2)); + } + } + + // binary(512) + for (int i = 10; i <= 12; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(3)); + } + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + if (null == byteValues) { + pstmt.setBytes(i, null); + } + else { + pstmt.setBytes(i, byteValues.get(4)); + } + } + + pstmt.execute(); } - - // binary(512) - for (int i = 10; i <= 12; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(3)); - } - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - if (null == byteValues) { - pstmt.setBytes(i, null); - } - else { - pstmt.setBytes(i, byteValues.get(4)); - } - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -809,60 +802,60 @@ protected static void populateBinaryNormalCase(LinkedList byteValues) th protected static void populateBinarySetObject(LinkedList byteValues) throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary(20) - for (int i = 1; i <= 3; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(0)); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary(20) + for (int i = 1; i <= 3; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(0)); + } + } + + // varbinary(50) + for (int i = 4; i <= 6; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(1)); + } + } + + // varbinary(max) + for (int i = 7; i <= 9; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(2)); + } + } + + // binary(512) + for (int i = 10; i <= 12; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(3)); + } + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, java.sql.Types.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(4)); + } + } + + pstmt.execute(); } - - // varbinary(50) - for (int i = 4; i <= 6; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(1)); - } - } - - // varbinary(max) - for (int i = 7; i <= 9; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(2)); - } - } - - // binary(512) - for (int i = 10; i <= 12; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(3)); - } - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, java.sql.Types.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(4)); - } - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -874,60 +867,60 @@ protected static void populateBinarySetObject(LinkedList byteValues) thr protected static void populateBinarySetObjectWithJDBCType(LinkedList byteValues) throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary(20) - for (int i = 1; i <= 3; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(0), JDBCType.BINARY); - } - } - - // varbinary(50) - for (int i = 4; i <= 6; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.VARBINARY); - } - else { - pstmt.setObject(i, byteValues.get(1), JDBCType.VARBINARY); - } - } - - // varbinary(max) - for (int i = 7; i <= 9; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.VARBINARY); - } - else { - pstmt.setObject(i, byteValues.get(2), JDBCType.VARBINARY); - } - } - - // binary(512) - for (int i = 10; i <= 12; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.BINARY); - } - else { - pstmt.setObject(i, byteValues.get(3), JDBCType.BINARY); - } - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - if (null == byteValues) { - pstmt.setObject(i, null, JDBCType.VARBINARY); - } - else { - pstmt.setObject(i, byteValues.get(4), JDBCType.VARBINARY); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary(20) + for (int i = 1; i <= 3; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(0), JDBCType.BINARY); + } + } + + // varbinary(50) + for (int i = 4; i <= 6; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.VARBINARY); + } + else { + pstmt.setObject(i, byteValues.get(1), JDBCType.VARBINARY); + } + } + + // varbinary(max) + for (int i = 7; i <= 9; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.VARBINARY); + } + else { + pstmt.setObject(i, byteValues.get(2), JDBCType.VARBINARY); + } + } + + // binary(512) + for (int i = 10; i <= 12; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.BINARY); + } + else { + pstmt.setObject(i, byteValues.get(3), JDBCType.BINARY); + } + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + if (null == byteValues) { + pstmt.setObject(i, null, JDBCType.VARBINARY); + } + else { + pstmt.setObject(i, byteValues.get(4), JDBCType.VARBINARY); + } + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -938,30 +931,30 @@ protected static void populateBinarySetObjectWithJDBCType(LinkedList byt protected static void populateBinaryNullCase() throws SQLException { String sql = "insert into " + binaryTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // binary - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.BINARY); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // binary + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.BINARY); + } + + // varbinary, varbinary(max) + for (int i = 4; i <= 9; i++) { + pstmt.setNull(i, java.sql.Types.VARBINARY); + } + + // binary512 + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.BINARY); + } + + // varbinary(8000) + for (int i = 13; i <= 15; i++) { + pstmt.setNull(i, java.sql.Types.VARBINARY); + } + + pstmt.execute(); } - - // varbinary, varbinary(max) - for (int i = 4; i <= 9; i++) { - pstmt.setNull(i, java.sql.Types.VARBINARY); - } - - // binary512 - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.BINARY); - } - - // varbinary(8000) - for (int i = 13; i <= 15; i++) { - pstmt.setNull(i, java.sql.Types.VARBINARY); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -974,60 +967,60 @@ protected static void populateCharNormalCase(String[] charValues) throws SQLExce String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setString(i, charValues[0]); - } - - // varchar - for (int i = 4; i <= 6; i++) { - pstmt.setString(i, charValues[1]); - } - - // varchar(max) - for (int i = 7; i <= 9; i++) { - pstmt.setString(i, charValues[2]); - } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setNString(i, charValues[3]); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setString(i, charValues[0]); + } + + // varchar + for (int i = 4; i <= 6; i++) { + pstmt.setString(i, charValues[1]); + } + + // varchar(max) + for (int i = 7; i <= 9; i++) { + pstmt.setString(i, charValues[2]); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setNString(i, charValues[3]); + } + + // nvarchar + for (int i = 13; i <= 15; i++) { + pstmt.setNString(i, charValues[4]); + } + + // varchar(max) + for (int i = 16; i <= 18; i++) { + pstmt.setNString(i, charValues[5]); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + if (null == charValues[6]) { + pstmt.setUniqueIdentifier(i, null); + } + else { + pstmt.setUniqueIdentifier(i, uid); + } + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setString(i, charValues[7]); + } + + // nvarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setNString(i, charValues[8]); + } + + pstmt.execute(); } - - // nvarchar - for (int i = 13; i <= 15; i++) { - pstmt.setNString(i, charValues[4]); - } - - // varchar(max) - for (int i = 16; i <= 18; i++) { - pstmt.setNString(i, charValues[5]); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - if (null == charValues[6]) { - pstmt.setUniqueIdentifier(i, null); - } - else { - pstmt.setUniqueIdentifier(i, uid); - } - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setString(i, charValues[7]); - } - - // nvarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setNString(i, charValues[8]); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1040,55 +1033,55 @@ protected static void populateCharSetObject(String[] charValues) throws SQLExcep String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, charValues[0]); - } - - // varchar - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, charValues[1]); - } - - // varchar(max) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, charValues[2], java.sql.Types.LONGVARCHAR); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, charValues[0]); + } + + // varchar + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, charValues[1]); + } + + // varchar(max) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, charValues[2], java.sql.Types.LONGVARCHAR); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, charValues[3], java.sql.Types.NCHAR); + } + + // nvarchar + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, charValues[4], java.sql.Types.NCHAR); + } + + // nvarchar(max) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, charValues[5], java.sql.Types.LONGNVARCHAR); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, charValues[7]); + } + + // nvarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setObject(i, charValues[8], java.sql.Types.NCHAR); + } + + pstmt.execute(); } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, charValues[3], java.sql.Types.NCHAR); - } - - // nvarchar - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, charValues[4], java.sql.Types.NCHAR); - } - - // nvarchar(max) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, charValues[5], java.sql.Types.LONGNVARCHAR); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, charValues[7]); - } - - // nvarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setObject(i, charValues[8], java.sql.Types.NCHAR); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1101,55 +1094,55 @@ protected static void populateCharSetObjectWithJDBCTypes(String[] charValues) th String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, charValues[0], JDBCType.CHAR); - } - - // varchar - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, charValues[1], JDBCType.VARCHAR); - } - - // varchar(max) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, charValues[2], JDBCType.LONGVARCHAR); - } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, charValues[3], JDBCType.NCHAR); - } - - // nvarchar - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, charValues[4], JDBCType.NVARCHAR); - } - - // nvarchar(max) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, charValues[5], JDBCType.LONGNVARCHAR); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, charValues[0], JDBCType.CHAR); + } + + // varchar + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, charValues[1], JDBCType.VARCHAR); + } + + // varchar(max) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, charValues[2], JDBCType.LONGVARCHAR); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, charValues[3], JDBCType.NCHAR); + } + + // nvarchar + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, charValues[4], JDBCType.NVARCHAR); + } + + // nvarchar(max) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, charValues[5], JDBCType.LONGNVARCHAR); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, charValues[6], microsoft.sql.Types.GUID); + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, charValues[7], JDBCType.VARCHAR); + } + + // vnarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setObject(i, charValues[8], JDBCType.NVARCHAR); + } + + pstmt.execute(); } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, charValues[7], JDBCType.VARCHAR); - } - - // vnarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setObject(i, charValues[8], JDBCType.NVARCHAR); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1161,46 +1154,46 @@ protected static void populateCharNullCase() throws SQLException { String sql = "insert into " + charTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // char - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.CHAR); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // char + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.CHAR); + } + + // varchar, varchar(max) + for (int i = 4; i <= 9; i++) { + pstmt.setNull(i, java.sql.Types.VARCHAR); + } + + // nchar + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.NCHAR); + } + + // nvarchar, varchar(max) + for (int i = 13; i <= 18; i++) { + pstmt.setNull(i, java.sql.Types.NVARCHAR); + } + + // uniqueidentifier + for (int i = 19; i <= 21; i++) { + pstmt.setNull(i, microsoft.sql.Types.GUID); + + } + + // varchar8000 + for (int i = 22; i <= 24; i++) { + pstmt.setNull(i, java.sql.Types.VARCHAR); + } + + // nvarchar4000 + for (int i = 25; i <= 27; i++) { + pstmt.setNull(i, java.sql.Types.NVARCHAR); + } + + pstmt.execute(); } - - // varchar, varchar(max) - for (int i = 4; i <= 9; i++) { - pstmt.setNull(i, java.sql.Types.VARCHAR); - } - - // nchar - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.NCHAR); - } - - // nvarchar, varchar(max) - for (int i = 13; i <= 18; i++) { - pstmt.setNull(i, java.sql.Types.NVARCHAR); - } - - // uniqueidentifier - for (int i = 19; i <= 21; i++) { - pstmt.setNull(i, microsoft.sql.Types.GUID); - - } - - // varchar8000 - for (int i = 22; i <= 24; i++) { - pstmt.setNull(i, java.sql.Types.VARCHAR); - } - - // nvarchar4000 - for (int i = 25; i <= 27; i++) { - pstmt.setNull(i, java.sql.Types.NVARCHAR); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1212,40 +1205,40 @@ protected static void populateCharNullCase() throws SQLException { protected static void populateDateNormalCase(LinkedList dateValues) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - pstmt.setDate(i, (Date) dateValues.get(0)); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + pstmt.setDate(i, (Date) dateValues.get(0)); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setTimestamp(i, (Timestamp) dateValues.get(1)); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(2)); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setTime(i, (Time) dateValues.get(3)); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setDateTime(i, (Timestamp) dateValues.get(4)); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setSmallDateTime(i, (Timestamp) dateValues.get(5)); + } + + pstmt.execute(); } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setTime(i, (Time) dateValues.get(3)); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setDateTime(i, (Timestamp) dateValues.get(4)); - } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setSmallDateTime(i, (Timestamp) dateValues.get(5)); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1257,25 +1250,25 @@ protected static void populateDateNormalCase(LinkedList dateValues) thro protected static void populateDateScaleNormalCase(LinkedList dateValues) throws SQLException { String sql = "insert into " + scaleDateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(2) - for (int i = 1; i <= 3; i++) { - pstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); - } - - // time(2) - for (int i = 4; i <= 6; i++) { - pstmt.setTime(i, (Time) dateValues.get(5), 2); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(2) + for (int i = 1; i <= 3; i++) { + pstmt.setTimestamp(i, (Timestamp) dateValues.get(4), 2); + } + + // time(2) + for (int i = 4; i <= 6; i++) { + pstmt.setTime(i, (Time) dateValues.get(5), 2); + } + + // datetimeoffset(2) + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); + } + + pstmt.execute(); } - - // datetimeoffset(2) - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, (DateTimeOffset) dateValues.get(6), 2); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1293,60 +1286,60 @@ protected static void populateDateSetObject(LinkedList dateValues, String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (Date) dateValues.get(0), java.sql.Types.DATE); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (Date) dateValues.get(0), JDBCType.DATE); - else - pstmt.setObject(i, (Date) dateValues.get(0)); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (Timestamp) dateValues.get(1), java.sql.Types.TIMESTAMP); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (Timestamp) dateValues.get(1), JDBCType.TIMESTAMP); - else - pstmt.setObject(i, (Timestamp) dateValues.get(1)); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); - else - pstmt.setObject(i, (DateTimeOffset) dateValues.get(2)); - } - - // time default - for (int i = 10; i <= 12; i++) { - if (setter.equalsIgnoreCase("setwithJavaType")) - pstmt.setObject(i, (Time) dateValues.get(3), java.sql.Types.TIME); - else if (setter.equalsIgnoreCase("setwithJDBCType")) - pstmt.setObject(i, (Time) dateValues.get(3), JDBCType.TIME); - else - pstmt.setObject(i, (Time) dateValues.get(3)); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, (Timestamp) dateValues.get(4), microsoft.sql.Types.DATETIME); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (Date) dateValues.get(0), java.sql.Types.DATE); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (Date) dateValues.get(0), JDBCType.DATE); + else + pstmt.setObject(i, (Date) dateValues.get(0)); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (Timestamp) dateValues.get(1), java.sql.Types.TIMESTAMP); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (Timestamp) dateValues.get(1), JDBCType.TIMESTAMP); + else + pstmt.setObject(i, (Timestamp) dateValues.get(1)); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (DateTimeOffset) dateValues.get(2), microsoft.sql.Types.DATETIMEOFFSET); + else + pstmt.setObject(i, (DateTimeOffset) dateValues.get(2)); + } + + // time default + for (int i = 10; i <= 12; i++) { + if (setter.equalsIgnoreCase("setwithJavaType")) + pstmt.setObject(i, (Time) dateValues.get(3), java.sql.Types.TIME); + else if (setter.equalsIgnoreCase("setwithJDBCType")) + pstmt.setObject(i, (Time) dateValues.get(3), JDBCType.TIME); + else + pstmt.setObject(i, (Time) dateValues.get(3)); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, (Timestamp) dateValues.get(4), microsoft.sql.Types.DATETIME); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, (Timestamp) dateValues.get(5), microsoft.sql.Types.SMALLDATETIME); + } + + pstmt.execute(); } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, (Timestamp) dateValues.get(5), microsoft.sql.Types.SMALLDATETIME); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1357,40 +1350,40 @@ else if (setter.equalsIgnoreCase("setwithJDBCType")) protected void populateDateSetObjectNull() throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.DATE); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, null, java.sql.Types.TIME); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.DATE); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, null, java.sql.Types.TIME); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIME); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.SMALLDATETIME); + } + + pstmt.execute(); } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIME); - } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.SMALLDATETIME); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1401,40 +1394,40 @@ protected void populateDateSetObjectNull() throws SQLException { protected static void populateDateNullCase() throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // date - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.DATE); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // date + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.DATE); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setNull(i, java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setNull(i, microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.TIME); + } + + // datetime + for (int i = 13; i <= 15; i++) { + pstmt.setNull(i, microsoft.sql.Types.DATETIME); + } + + // smalldatetime + for (int i = 16; i <= 18; i++) { + pstmt.setNull(i, microsoft.sql.Types.SMALLDATETIME); + } + + pstmt.execute(); } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setNull(i, java.sql.Types.TIMESTAMP); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setNull(i, microsoft.sql.Types.DATETIMEOFFSET); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.TIME); - } - - // datetime - for (int i = 13; i <= 15; i++) { - pstmt.setNull(i, microsoft.sql.Types.DATETIME); - } - - // smalldatetime - for (int i = 16; i <= 18; i++) { - pstmt.setNull(i, microsoft.sql.Types.SMALLDATETIME); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1447,101 +1440,101 @@ protected static void populateNumeric(String[] values) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setShort(i, Short.valueOf(values[1])); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setShort(i, Short.valueOf(values[2])); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setInt(i, Integer.valueOf(values[3])); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setLong(i, Long.valueOf(values[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setDouble(i, Double.valueOf(values[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setDouble(i, Double.valueOf(values[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setFloat(i, Float.valueOf(values[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (values[8].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(values[8]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(values[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[9]), 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (values[10].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(values[10]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(values[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[11]), 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setSmallMoney(i, new BigDecimal(values[12])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (values[0].equalsIgnoreCase("true")) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setShort(i, Short.valueOf(values[1])); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setShort(i, Short.valueOf(values[2])); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setInt(i, Integer.valueOf(values[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setLong(i, Long.valueOf(values[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setDouble(i, Double.valueOf(values[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setDouble(i, Double.valueOf(values[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setFloat(i, Float.valueOf(values[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (values[8].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(values[8]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(values[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[9]), 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (values[10].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(values[10]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(values[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[11]), 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setSmallMoney(i, new BigDecimal(values[12])); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setMoney(i, new BigDecimal(values[13])); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[14]), 28, 4); + } + + // numeric(28,4) + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, new BigDecimal(values[15]), 28, 4); + } + + pstmt.execute(); } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setMoney(i, new BigDecimal(values[13])); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[14]), 28, 4); - } - - // numeric(28,4) - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, new BigDecimal(values[15]), 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1554,101 +1547,101 @@ protected static void populateNumericSetObject(String[] values) throws SQLExcept String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { - pstmt.setObject(i, true); - } - else { - pstmt.setObject(i, false); - } + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (values[0].equalsIgnoreCase("true")) { + pstmt.setObject(i, true); + } + else { + pstmt.setObject(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, Short.valueOf(values[1])); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, Short.valueOf(values[2])); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, Integer.valueOf(values[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, Long.valueOf(values[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, Double.valueOf(values[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, Double.valueOf(values[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, Float.valueOf(values[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); + } + + pstmt.execute(); } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, Short.valueOf(values[1])); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, Short.valueOf(values[2])); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, Integer.valueOf(values[3])); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, Long.valueOf(values[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, Double.valueOf(values[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, Double.valueOf(values[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, Float.valueOf(values[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1661,101 +1654,101 @@ protected static void populateNumericSetObjectWithJDBCTypes(String[] values) thr String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (values[0].equalsIgnoreCase("true")) { - pstmt.setObject(i, true); - } - else { - pstmt.setObject(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, Short.valueOf(values[1]), JDBCType.TINYINT); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, Short.valueOf(values[2]), JDBCType.SMALLINT); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, Integer.valueOf(values[3]), JDBCType.INTEGER); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (values[0].equalsIgnoreCase("true")) { + pstmt.setObject(i, true); + } + else { + pstmt.setObject(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, Short.valueOf(values[1]), JDBCType.TINYINT); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, Short.valueOf(values[2]), JDBCType.SMALLINT); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, Integer.valueOf(values[3]), JDBCType.INTEGER); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, Long.valueOf(values[4]), JDBCType.BIGINT); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, Double.valueOf(values[5]), JDBCType.DOUBLE); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, Double.valueOf(values[6]), JDBCType.DOUBLE); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, Float.valueOf(values[7]), JDBCType.REAL); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (RandomData.returnZero) + pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); + else + pstmt.setObject(i, new BigDecimal(values[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); + } + + pstmt.execute(); } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, Long.valueOf(values[4]), JDBCType.BIGINT); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, Double.valueOf(values[5]), JDBCType.DOUBLE); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, Double.valueOf(values[6]), JDBCType.DOUBLE); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, Float.valueOf(values[7]), JDBCType.REAL); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[8]), java.sql.Types.DECIMAL, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setObject(i, new BigDecimal(values[9]), java.sql.Types.DECIMAL, 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (RandomData.returnZero) - pstmt.setObject(i, new BigDecimal(values[10]), java.sql.Types.NUMERIC, 18, 0); - else - pstmt.setObject(i, new BigDecimal(values[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setObject(i, new BigDecimal(values[11]), java.sql.Types.NUMERIC, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setObject(i, new BigDecimal(values[12]), microsoft.sql.Types.SMALLMONEY); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setObject(i, new BigDecimal(values[13]), microsoft.sql.Types.MONEY); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setObject(i, new BigDecimal(values[14]), java.sql.Types.DECIMAL, 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setObject(i, new BigDecimal(values[15]), java.sql.Types.NUMERIC, 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1767,90 +1760,90 @@ protected static void populateNumericSetObjectNull() throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.BIT); - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.TINYINT); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, java.sql.Types.SMALLINT); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, null, java.sql.Types.INTEGER); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, null, java.sql.Types.BIGINT); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, null, java.sql.Types.DOUBLE); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setObject(i, null, java.sql.Types.DOUBLE); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.BIT); + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.TINYINT); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, java.sql.Types.SMALLINT); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, null, java.sql.Types.INTEGER); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, null, java.sql.Types.BIGINT); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, null, java.sql.Types.DOUBLE); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setObject(i, null, java.sql.Types.DOUBLE); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setObject(i, null, java.sql.Types.REAL); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.SMALLMONEY); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.MONEY); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL, 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC, 28, 4); + } + + pstmt.execute(); } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setObject(i, null, java.sql.Types.REAL); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL, 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.SMALLMONEY); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.MONEY); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL, 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC, 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1865,89 +1858,89 @@ protected static void populateNumericNullCase(String[] values) throws SQLExcepti + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - pstmt.setNull(i, java.sql.Types.BIT); - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setNull(i, java.sql.Types.TINYINT); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setNull(i, java.sql.Types.SMALLINT); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setNull(i, java.sql.Types.INTEGER); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setNull(i, java.sql.Types.BIGINT); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setNull(i, java.sql.Types.DOUBLE); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setNull(i, java.sql.Types.DOUBLE); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setNull(i, java.sql.Types.REAL); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - pstmt.setBigDecimal(i, null); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, null, 10, 5); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + pstmt.setNull(i, java.sql.Types.BIT); + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setNull(i, java.sql.Types.TINYINT); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setNull(i, java.sql.Types.SMALLINT); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setNull(i, java.sql.Types.INTEGER); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setNull(i, java.sql.Types.BIGINT); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setNull(i, java.sql.Types.DOUBLE); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setNull(i, java.sql.Types.DOUBLE); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setNull(i, java.sql.Types.REAL); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + pstmt.setBigDecimal(i, null); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, null, 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + pstmt.setBigDecimal(i, null); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, null, 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setSmallMoney(i, null); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setMoney(i, null); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setBigDecimal(i, null, 28, 4); + } + + // decimal(28,4) + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, null, 28, 4); + } + pstmt.execute(); } - - // numeric - for (int i = 31; i <= 33; i++) { - pstmt.setBigDecimal(i, null); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, null, 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setSmallMoney(i, null); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setMoney(i, null); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setBigDecimal(i, null, 28, 4); - } - - // decimal(28,4) - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, null, 28, 4); - } - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -1962,105 +1955,105 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (numericValues[0].equalsIgnoreCase("true")) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - if (1 == Integer.valueOf(numericValues[1])) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // smallint - for (int i = 7; i <= 9; i++) { - if (numericValues[2].equalsIgnoreCase("255")) { - pstmt.setByte(i, (byte) 255); - } - else { - pstmt.setByte(i, Byte.valueOf(numericValues[2])); - } - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setShort(i, Short.valueOf(numericValues[3])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (numericValues[0].equalsIgnoreCase("true")) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + if (1 == Integer.valueOf(numericValues[1])) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // smallint + for (int i = 7; i <= 9; i++) { + if (numericValues[2].equalsIgnoreCase("255")) { + pstmt.setByte(i, (byte) 255); + } + else { + pstmt.setByte(i, Byte.valueOf(numericValues[2])); + } + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setShort(i, Short.valueOf(numericValues[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setInt(i, Integer.valueOf(numericValues[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setDouble(i, Double.valueOf(numericValues[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setDouble(i, Double.valueOf(numericValues[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setFloat(i, Float.valueOf(numericValues[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); + } + + // small money + for (int i = 37; i <= 39; i++) { + pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); + } + + // money + for (int i = 40; i <= 42; i++) { + pstmt.setSmallMoney(i, new BigDecimal(numericValues[13])); + } + + // decimal(28,4) + for (int i = 43; i <= 45; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); + } + + // numeric + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); + } + + pstmt.execute(); } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setInt(i, Integer.valueOf(numericValues[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setDouble(i, Double.valueOf(numericValues[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setDouble(i, Double.valueOf(numericValues[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setFloat(i, Float.valueOf(numericValues[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); - } - - // small money - for (int i = 37; i <= 39; i++) { - pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); - } - - // money - for (int i = 40; i <= 42; i++) { - pstmt.setSmallMoney(i, new BigDecimal(numericValues[13])); - } - - // decimal(28,4) - for (int i = 43; i <= 45; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); - } - - // numeric - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } /** @@ -2069,7 +2062,7 @@ protected static void populateNumericNormalCase(String[] numericValues) throws S * @throws SQLServerException * @throws SQLException */ - private static void dropCEK() throws SQLServerException, SQLException { + private static void dropCEK(SQLServerStatement stmt) throws SQLServerException, SQLException { String cekSql = " if exists (SELECT name from sys.column_encryption_keys where name='" + cekName + "')" + " begin" + " drop column encryption key " + cekName + " end"; stmt.execute(cekSql); @@ -2081,7 +2074,7 @@ private static void dropCEK() throws SQLServerException, SQLException { * @throws SQLServerException * @throws SQLException */ - private static void dropCMK() throws SQLServerException, SQLException { + private static void dropCMK(SQLServerStatement stmt) throws SQLServerException, SQLException { String cekSql = " if exists (SELECT name from sys.column_master_keys where name='" + cmkName + "')" + " begin" + " drop column master key " + cmkName + " end"; stmt.execute(cekSql); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java index 9c23e98c1..cc6a67e29 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/CallableStatementTest.java @@ -42,9 +42,6 @@ @RunWith(JUnitPlatform.class) public class CallableStatementTest extends AESetup { - private static SQLServerPreparedStatement pstmt = null; - private static SQLServerCallableStatement callableStatement = null; - private static String multiStatementsProcedure = "multiStatementsProcedure"; private static String inputProcedure = "inputProcedure"; @@ -470,118 +467,120 @@ private static void createTables() throws SQLException { private static void populateTable4() throws SQLException { String sql = "insert into " + table4 + " values( " + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { - // bit - for (int i = 1; i <= 3; i++) { - pstmt.setInt(i, Integer.parseInt(numericValues[3])); + // bit + for (int i = 1; i <= 3; i++) { + pstmt.setInt(i, Integer.parseInt(numericValues[3])); + } + + pstmt.execute(); } - - pstmt.execute(); } private static void populateTable3() throws SQLException { String sql = "insert into " + table3 + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // bit - for (int i = 1; i <= 3; i++) { - if (numericValues[0].equalsIgnoreCase("true")) { - pstmt.setBoolean(i, true); - } - else { - pstmt.setBoolean(i, false); - } - } - - // tinyint - for (int i = 4; i <= 6; i++) { - pstmt.setShort(i, Short.valueOf(numericValues[1])); - } - - // smallint - for (int i = 7; i <= 9; i++) { - pstmt.setShort(i, Short.parseShort(numericValues[2])); - } - - // int - for (int i = 10; i <= 12; i++) { - pstmt.setInt(i, Integer.parseInt(numericValues[3])); - } - - // bigint - for (int i = 13; i <= 15; i++) { - pstmt.setLong(i, Long.parseLong(numericValues[4])); - } - - // float default - for (int i = 16; i <= 18; i++) { - pstmt.setDouble(i, Double.parseDouble(numericValues[5])); - } - - // float(30) - for (int i = 19; i <= 21; i++) { - pstmt.setDouble(i, Double.parseDouble(numericValues[6])); - } - - // real - for (int i = 22; i <= 24; i++) { - pstmt.setFloat(i, Float.parseFloat(numericValues[7])); - } - - // decimal default - for (int i = 25; i <= 27; i++) { - if (numericValues[8].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(numericValues[8]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); - } - - // decimal(10,5) - for (int i = 28; i <= 30; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); - } - - // numeric - for (int i = 31; i <= 33; i++) { - if (numericValues[10].equalsIgnoreCase("0")) - pstmt.setBigDecimal(i, new BigDecimal(numericValues[10]), 18, 0); - else - pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); - } - - // numeric(8,2) - for (int i = 34; i <= 36; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); - } - - // int2 - for (int i = 37; i <= 39; i++) { - pstmt.setInt(i, Integer.parseInt(numericValues[3])); - } - // smallmoney - for (int i = 40; i <= 42; i++) { - pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); - } - - // money - for (int i = 43; i <= 45; i++) { - pstmt.setMoney(i, new BigDecimal(numericValues[13])); - } - - // decimal(28,4) - for (int i = 46; i <= 48; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); - } - - // numeric(28,4) - for (int i = 49; i <= 51; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // bit + for (int i = 1; i <= 3; i++) { + if (numericValues[0].equalsIgnoreCase("true")) { + pstmt.setBoolean(i, true); + } + else { + pstmt.setBoolean(i, false); + } + } + + // tinyint + for (int i = 4; i <= 6; i++) { + pstmt.setShort(i, Short.valueOf(numericValues[1])); + } + + // smallint + for (int i = 7; i <= 9; i++) { + pstmt.setShort(i, Short.parseShort(numericValues[2])); + } + + // int + for (int i = 10; i <= 12; i++) { + pstmt.setInt(i, Integer.parseInt(numericValues[3])); + } + + // bigint + for (int i = 13; i <= 15; i++) { + pstmt.setLong(i, Long.parseLong(numericValues[4])); + } + + // float default + for (int i = 16; i <= 18; i++) { + pstmt.setDouble(i, Double.parseDouble(numericValues[5])); + } + + // float(30) + for (int i = 19; i <= 21; i++) { + pstmt.setDouble(i, Double.parseDouble(numericValues[6])); + } + + // real + for (int i = 22; i <= 24; i++) { + pstmt.setFloat(i, Float.parseFloat(numericValues[7])); + } + + // decimal default + for (int i = 25; i <= 27; i++) { + if (numericValues[8].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(numericValues[8]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(numericValues[8])); + } + + // decimal(10,5) + for (int i = 28; i <= 30; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[9]), 10, 5); + } + + // numeric + for (int i = 31; i <= 33; i++) { + if (numericValues[10].equalsIgnoreCase("0")) + pstmt.setBigDecimal(i, new BigDecimal(numericValues[10]), 18, 0); + else + pstmt.setBigDecimal(i, new BigDecimal(numericValues[10])); + } + + // numeric(8,2) + for (int i = 34; i <= 36; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[11]), 8, 2); + } + + // int2 + for (int i = 37; i <= 39; i++) { + pstmt.setInt(i, Integer.parseInt(numericValues[3])); + } + // smallmoney + for (int i = 40; i <= 42; i++) { + pstmt.setSmallMoney(i, new BigDecimal(numericValues[12])); + } + + // money + for (int i = 43; i <= 45; i++) { + pstmt.setMoney(i, new BigDecimal(numericValues[13])); + } + + // decimal(28,4) + for (int i = 46; i <= 48; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[14]), 28, 4); + } + + // numeric(28,4) + for (int i = 49; i <= 51; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numericValues[15]), 28, 4); + } + + pstmt.execute(); } - - pstmt.execute(); } private void createMultiInsertionSelection() throws SQLException { @@ -600,44 +599,39 @@ private void MultiInsertionSelection() throws SQLException { try { String sql = "{call " + multiStatementsProcedure + " (?,?,?,?,?,?)}"; - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - - // char, varchar - for (int i = 1; i <= 3; i++) { - callableStatement.setString(i, charValues[0]); - } - - for (int i = 4; i <= 6; i++) { - callableStatement.setString(i, charValues[1]); - } - - boolean results = callableStatement.execute(); - - // skip update count which is given by insertion - while (false == results && (-1) != callableStatement.getUpdateCount()) { - results = callableStatement.getMoreResults(); - } - - while (results) { - rs = callableStatement.getResultSet(); - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetString(rs, numberOfColumns); - } - rs.close(); - results = callableStatement.getMoreResults(); + try(SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { + + // char, varchar + for (int i = 1; i <= 3; i++) { + callableStatement.setString(i, charValues[0]); + } + + for (int i = 4; i <= 6; i++) { + callableStatement.setString(i, charValues[1]); + } + + boolean results = callableStatement.execute(); + + // skip update count which is given by insertion + while (false == results && (-1) != callableStatement.getUpdateCount()) { + results = callableStatement.getMoreResults(); + } + + while (results) { + try(ResultSet rs = callableStatement.getResultSet()) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + + while (rs.next()) { + testGetString(rs, numberOfColumns); + } + } + results = callableStatement.getMoreResults(); + } } } catch (SQLException e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testGetString(ResultSet rs, @@ -675,8 +669,7 @@ private void createInputProcedure() throws SQLException { private void testInputProcedure(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(values[3])); if (RandomData.returnZero) @@ -703,19 +696,14 @@ private void testInputProcedure(String sql, callableStatement.setBigDecimal(14, new BigDecimal(values[14]), 28, 4); callableStatement.setBigDecimal(15, new BigDecimal(values[15]), 28, 4); - SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery(); - rs.next(); - - assertEquals(rs.getString(1), values[3], "" + "Test for input parameter fails.\n"); + try (SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery()) { + rs.next(); + assertEquals(rs.getString(1), values[3], "" + "Test for input parameter fails.\n"); + } } catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createInputProcedure2() throws SQLException { @@ -735,8 +723,7 @@ private void createInputProcedure2() throws SQLException { private void testInputProcedure2(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setString(1, charValues[1]); callableStatement.setUniqueIdentifier(2, charValues[6]); @@ -747,26 +734,21 @@ private void testInputProcedure2(String sql) throws SQLException { callableStatement.setString(7, charValues[7]); callableStatement.setNString(8, charValues[8]); - SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery(); - rs.next(); - - assertEquals(rs.getString(1).trim(), charValues[1], "Test for input parameter fails.\n"); - assertEquals(rs.getUniqueIdentifier(2), charValues[6].toUpperCase(), "Test for input parameter fails.\n"); - assertEquals(rs.getString(3).trim(), charValues[2], "Test for input parameter fails.\n"); - assertEquals(rs.getString(4).trim(), charValues[3], "Test for input parameter fails.\n"); - assertEquals(rs.getString(5).trim(), charValues[4], "Test for input parameter fails.\n"); - assertEquals(rs.getString(6).trim(), charValues[5], "Test for input parameter fails.\n"); - assertEquals(rs.getString(7).trim(), charValues[7], "Test for input parameter fails.\n"); - assertEquals(rs.getString(8).trim(), charValues[8], "Test for input parameter fails.\n"); + try (SQLServerResultSet rs = (SQLServerResultSet) callableStatement.executeQuery()) { + rs.next(); + assertEquals(rs.getString(1).trim(), charValues[1], "Test for input parameter fails.\n"); + assertEquals(rs.getUniqueIdentifier(2), charValues[6].toUpperCase(), "Test for input parameter fails.\n"); + assertEquals(rs.getString(3).trim(), charValues[2], "Test for input parameter fails.\n"); + assertEquals(rs.getString(4).trim(), charValues[3], "Test for input parameter fails.\n"); + assertEquals(rs.getString(5).trim(), charValues[4], "Test for input parameter fails.\n"); + assertEquals(rs.getString(6).trim(), charValues[5], "Test for input parameter fails.\n"); + assertEquals(rs.getString(7).trim(), charValues[7], "Test for input parameter fails.\n"); + assertEquals(rs.getString(8).trim(), charValues[8], "Test for input parameter fails.\n"); + } } catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure3() throws SQLException { @@ -782,8 +764,7 @@ private void createOutputProcedure3() throws SQLException { private void testOutputProcedure3RandomOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -808,17 +789,11 @@ private void testOutputProcedure3RandomOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure3Inorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -834,17 +809,11 @@ private void testOutputProcedure3Inorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -860,11 +829,6 @@ private void testOutputProcedure3ReverseOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure2() throws SQLException { @@ -885,8 +849,7 @@ private void createOutputProcedure2() throws SQLException { private void testOutputProcedure2RandomOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -934,18 +897,12 @@ private void testOutputProcedure2RandomOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure2Inorder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -993,18 +950,12 @@ private void testOutputProcedure2Inorder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedure2ReverseOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); @@ -1053,11 +1004,6 @@ private void testOutputProcedure2ReverseOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure() throws SQLException { @@ -1076,8 +1022,7 @@ private void createOutputProcedure() throws SQLException { private void testOutputProcedureRandomOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1121,18 +1066,12 @@ private void testOutputProcedureRandomOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureInorder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1169,18 +1108,12 @@ private void testOutputProcedureInorder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureReverseOrder(String sql, String[] values) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -1216,11 +1149,6 @@ private void testOutputProcedureReverseOrder(String sql, catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createInOutProcedure() throws SQLException { @@ -1236,8 +1164,7 @@ private void createInOutProcedure() throws SQLException { private void testInOutProcedure(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.setInt(1, Integer.parseInt(numericValues[3])); callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); @@ -1250,11 +1177,6 @@ private void testInOutProcedure(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedure() throws SQLException { @@ -1271,8 +1193,7 @@ private void createMixedProcedure() throws SQLException { private void testMixedProcedure(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.setInt(2, Integer.parseInt(numericValues[3])); @@ -1296,11 +1217,6 @@ private void testMixedProcedure(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedure2() throws SQLException { @@ -1317,8 +1233,7 @@ private void createMixedProcedure2() throws SQLException { private void testMixedProcedure2RandomOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1348,17 +1263,11 @@ private void testMixedProcedure2RandomOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedure2Inorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1375,11 +1284,6 @@ private void testMixedProcedure2Inorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedure3() throws SQLException { @@ -1395,8 +1299,7 @@ private void createMixedProcedure3() throws SQLException { private void testMixedProcedure3RandomOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1426,17 +1329,11 @@ private void testMixedProcedure3RandomOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedure3Inorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1453,17 +1350,11 @@ private void testMixedProcedure3Inorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.BIGINT); callableStatement.registerOutParameter(2, java.sql.Types.FLOAT); @@ -1480,11 +1371,6 @@ private void testMixedProcedure3ReverseOrder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createMixedProcedureNumericPrcisionScale() throws SQLException { @@ -1503,8 +1389,7 @@ private void createMixedProcedureNumericPrcisionScale() throws SQLException { private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQLException { - try { - SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter(2, java.sql.Types.DECIMAL, 10, 5); @@ -1530,17 +1415,11 @@ private void testMixedProcedureNumericPrcisionScaleInorder(String sql) throws SQ catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) throws SQLException { - try { - SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter("p1", java.sql.Types.DECIMAL, 18, 0); callableStatement.registerOutParameter("p2", java.sql.Types.DECIMAL, 10, 5); @@ -1566,11 +1445,6 @@ private void testMixedProcedureNumericPrcisionScaleParameterName(String sql) thr catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedureChar() throws SQLException { @@ -1589,7 +1463,7 @@ private void createOutputProcedureChar() throws SQLException { private void testOutputProcedureCharInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1632,16 +1506,11 @@ private void testOutputProcedureCharInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureCharInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.CHAR, 20, 0); callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR, 50, 0); callableStatement.registerOutParameter(3, java.sql.Types.NCHAR, 30, 0); @@ -1687,11 +1556,6 @@ private void testOutputProcedureCharInorderObject(String sql) throws SQLExceptio catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedureNumeric() throws SQLException { @@ -1788,11 +1652,6 @@ private void testOutputProcedureNumericInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testcoerctionsOutputProcedureNumericInorder(String sql) throws SQLException { @@ -2009,11 +1868,6 @@ else if (value.toString().equals("0") || value.equals(false) || value.toString() catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private Object createValue(Class coercion, @@ -2037,7 +1891,6 @@ private Object createValue(Class coercion, return new BigDecimal(numericValues[index]); } catch (java.lang.NumberFormatException e) { - return null; } return null; } @@ -2156,11 +2009,6 @@ private void testOutputProcedureBinaryInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureBinaryInorderObject(String sql) throws SQLException { @@ -2199,11 +2047,6 @@ private void testOutputProcedureBinaryInorderObject(String sql) throws SQLExcept catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureBinaryInorderString(String sql) throws SQLException { @@ -2217,37 +2060,30 @@ private void testOutputProcedureBinaryInorderString(String sql) throws SQLExcept callableStatement.execute(); int index = 1; - try { - for (int i = 0; i < byteValues.size(); i++) { - String stringValue1 = ("" + callableStatement.getString(index)).trim(); + for (int i = 0; i < byteValues.size(); i++) { + String stringValue1 = ("" + callableStatement.getString(index)).trim(); - StringBuffer expected = new StringBuffer(); - String expectedStr = null; + StringBuffer expected = new StringBuffer(); + String expectedStr = null; - if (null != byteValues.get(i)) { - for (byte b : byteValues.get(i)) { - expected.append(String.format("%02X", b)); - } - expectedStr = "" + expected.toString(); - } - else { - expectedStr = "null"; - } - try { - assertEquals(stringValue1.startsWith(expectedStr), true, - "\nDecryption failed with getString(): " + stringValue1 + ".\nExpected Value: " + expectedStr); - } - catch (Exception e) { - fail(e.toString()); - } - finally { - index++; + if (null != byteValues.get(i)) { + for (byte b : byteValues.get(i)) { + expected.append(String.format("%02X", b)); } + expectedStr = "" + expected.toString(); } - } - finally { - if (null != callableStatement) { - callableStatement.close(); + else { + expectedStr = "null"; + } + try { + assertEquals(stringValue1.startsWith(expectedStr), true, + "\nDecryption failed with getString(): " + stringValue1 + ".\nExpected Value: " + expectedStr); + } + catch (Exception e) { + fail(e.toString()); + } + finally { + index++; } } } @@ -2419,7 +2255,7 @@ private void createOutputProcedureDate() throws SQLException { private void testOutputProcedureDateInorder(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2459,16 +2295,11 @@ private void testOutputProcedureDateInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testOutputProcedureDateInorderObject(String sql) throws SQLException { - try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting);) { + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.DATE); callableStatement.registerOutParameter(2, java.sql.Types.DATE); callableStatement.registerOutParameter(3, java.sql.Types.TIMESTAMP); @@ -2508,11 +2339,6 @@ private void testOutputProcedureDateInorderObject(String sql) throws SQLExceptio catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedureBatch() throws SQLException { @@ -2531,8 +2357,7 @@ private void createOutputProcedureBatch() throws SQLException { private void testOutputProcedureBatchInorder(String sql) throws SQLException { - try { - callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting); + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) Util.getCallableStmt(con, sql, stmtColEncSetting)) { callableStatement.registerOutParameter(1, java.sql.Types.INTEGER); callableStatement.registerOutParameter(2, java.sql.Types.DOUBLE); @@ -2555,11 +2380,6 @@ private void testOutputProcedureBatchInorder(String sql) throws SQLException { catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void createOutputProcedure4() throws SQLException { @@ -2614,11 +2434,6 @@ private void testMixedProcedureDateScaleInorder(String sql) throws SQLException catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQLException { @@ -2645,10 +2460,5 @@ private void testMixedProcedureDateScaleWithParameterName(String sql) throws SQL catch (Exception e) { fail(e.toString()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java index 0c1de2266..06e44276b 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/JDBCEncryptionDecryptionTest.java @@ -512,68 +512,46 @@ public void testNumericNormalization() throws SQLException { private void testChar(SQLServerStatement stmt, String[] values) throws SQLException { String sql = "select * from " + charTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - if (stmt == null) { - rs = pstmt.executeQuery(); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + testGetString(rs, numberOfColumns, values); + testGetObject(rs, numberOfColumns, values); + } + } } - else { - rs = stmt.executeQuery(sql); - } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, values); - testGetObject(rs, numberOfColumns, values); - } - - Util.close(rs, pstmt, null); } private void testBinary(SQLServerStatement stmt, LinkedList values) throws SQLException { String sql = "select * from " + binaryTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - if (stmt == null) { - rs = pstmt.executeQuery(); - } - else { - rs = stmt.executeQuery(sql); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + testGetStringForBinary(rs, numberOfColumns, values); + testGetBytes(rs, numberOfColumns, values); + testGetObjectForBinary(rs, numberOfColumns, values); + } + } } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetStringForBinary(rs, numberOfColumns, values); - testGetBytes(rs, numberOfColumns, values); - testGetObjectForBinary(rs, numberOfColumns, values); - } - - Util.close(rs, pstmt, null); } private void testDate(SQLServerStatement stmt, LinkedList values1) throws SQLException { - String sql = "select * from " + dateTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - ResultSet rs = null; - if (stmt == null) { - rs = pstmt.executeQuery(); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(ResultSet rs = (stmt == null) ? pstmt.executeQuery() : stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + // testGetStringForDate(rs, numberOfColumns, values1); //TODO: Disabling, since getString throws verification error for zero temporal + // types + testGetObjectForTemporal(rs, numberOfColumns, values1); + testGetDate(rs, numberOfColumns, values1); + } + } } - else { - rs = stmt.executeQuery(sql); - } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - // testGetStringForDate(rs, numberOfColumns, values1); //TODO: Disabling, since getString throws verification error for zero temporal - // types - testGetObjectForTemporal(rs, numberOfColumns, values1); - testGetDate(rs, numberOfColumns, values1); - } - - Util.close(rs, pstmt, null); } private void testGetObject(ResultSet rs, @@ -948,29 +926,22 @@ private void testNumeric(Statement stmt, String[] numericValues, boolean isNull) throws SQLException { String sql = "select * from " + numericTable; - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - SQLServerResultSet rs = null; - if (stmt == null) { - rs = (SQLServerResultSet) pstmt.executeQuery(); - } - else { - rs = (SQLServerResultSet) stmt.executeQuery(sql); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + try(SQLServerResultSet rs = (stmt == null) ? (SQLServerResultSet) pstmt.executeQuery() : (SQLServerResultSet) stmt.executeQuery(sql)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + while (rs.next()) { + testGetString(rs, numberOfColumns, numericValues); + testGetObject(rs, numberOfColumns, numericValues); + testGetBigDecimal(rs, numberOfColumns, numericValues); + if (!isNull) + testWithSpecifiedtype(rs, numberOfColumns, numericValues); + else { + String[] nullNumericValues = {"false", "0", "0", "0", "0", "0.0", "0.0", "0.0", null, null, null, null, null, null, null, null}; + testWithSpecifiedtype(rs, numberOfColumns, nullNumericValues); + } + } + } } - int numberOfColumns = rs.getMetaData().getColumnCount(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, numericValues); - testGetObject(rs, numberOfColumns, numericValues); - testGetBigDecimal(rs, numberOfColumns, numericValues); - if (!isNull) - testWithSpecifiedtype(rs, numberOfColumns, numericValues); - else { - String[] nullNumericValues = {"false", "0", "0", "0", "0", "0.0", "0.0", "0.0", null, null, null, null, null, null, null, null}; - testWithSpecifiedtype(rs, numberOfColumns, nullNumericValues); - } - } - - Util.close(rs, pstmt, null); } private void testWithSpecifiedtype(SQLServerResultSet rs, diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java index 23dede74d..4d7b8b3d0 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/AlwaysEncrypted/PrecisionScaleTest.java @@ -155,38 +155,32 @@ public void testDateScale5Null() throws Exception { private void testNumeric(String[] numeric) throws SQLException { - ResultSet rs = stmt.executeQuery("select * from " + numericTable); - int numberOfColumns = rs.getMetaData().getColumnCount(); - - ArrayList skipMax = new ArrayList<>(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, skipMax, numeric); - testGetBigDecimal(rs, numberOfColumns, numeric); - testGetObject(rs, numberOfColumns, skipMax, numeric); - } - - if (null != rs) { - rs.close(); + try(ResultSet rs = stmt.executeQuery("select * from " + numericTable)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + + ArrayList skipMax = new ArrayList<>(); + + while (rs.next()) { + testGetString(rs, numberOfColumns, skipMax, numeric); + testGetBigDecimal(rs, numberOfColumns, numeric); + testGetObject(rs, numberOfColumns, skipMax, numeric); + } } } private void testDate(String[] dateNormalCase, String[] dateSetObject) throws Exception { - ResultSet rs = stmt.executeQuery("select * from " + dateTable); - int numberOfColumns = rs.getMetaData().getColumnCount(); - - ArrayList skipMax = new ArrayList<>(); - - while (rs.next()) { - testGetString(rs, numberOfColumns, skipMax, dateNormalCase); - testGetObject(rs, numberOfColumns, skipMax, dateSetObject); - testGetDate(rs, numberOfColumns, dateSetObject); - } - - if (null != rs) { - rs.close(); + try(ResultSet rs = stmt.executeQuery("select * from " + dateTable)) { + int numberOfColumns = rs.getMetaData().getColumnCount(); + + ArrayList skipMax = new ArrayList<>(); + + while (rs.next()) { + testGetString(rs, numberOfColumns, skipMax, dateNormalCase); + testGetObject(rs, numberOfColumns, skipMax, dateSetObject); + testGetDate(rs, numberOfColumns, dateSetObject); + } } } @@ -351,79 +345,79 @@ private void testGetDate(ResultSet rs, private void populateDateNormalCase(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setTimestamp(i, new Timestamp(date.getTime()), scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setTimestamp(i, new Timestamp(date.getTime())); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1)); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setTime(i, new Time(date.getTime())); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setTime(i, new Time(date.getTime()), scale); - } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), scale); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setTimestamp(i, new Timestamp(date.getTime()), scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setTimestamp(i, new Timestamp(date.getTime())); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1)); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setTime(i, new Time(date.getTime())); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setTime(i, new Time(date.getTime()), scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setDateTimeOffset(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), scale); + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateDateNormalCaseNull(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setTimestamp(i, null, scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setTimestamp(i, null); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setDateTimeOffset(i, null); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setTime(i, null); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setTime(i, null, scale); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setTimestamp(i, null, scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setTimestamp(i, null); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setDateTimeOffset(i, null); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setTime(i, null); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setTime(i, null, scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setDateTimeOffset(i, null, scale); + } + + pstmt.execute(); } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setDateTimeOffset(i, null, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateNumericNormalCase(String[] numeric, @@ -431,25 +425,25 @@ private void populateNumericNormalCase(String[] numeric, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // float(30) - for (int i = 1; i <= 3; i++) { - pstmt.setDouble(i, Double.valueOf(numeric[0])); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // float(30) + for (int i = 1; i <= 3; i++) { + pstmt.setDouble(i, Double.valueOf(numeric[0])); + } + + // decimal(10,5) + for (int i = 4; i <= 6; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numeric[1]), precision, scale); + } + + // numeric(8,2) + for (int i = 7; i <= 9; i++) { + pstmt.setBigDecimal(i, new BigDecimal(numeric[2]), precision, scale); + } + + pstmt.execute(); } - - // decimal(10,5) - for (int i = 4; i <= 6; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numeric[1]), precision, scale); - } - - // numeric(8,2) - for (int i = 7; i <= 9; i++) { - pstmt.setBigDecimal(i, new BigDecimal(numeric[2]), precision, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateNumericSetObject(String[] numeric, @@ -457,129 +451,129 @@ private void populateNumericSetObject(String[] numeric, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // float(30) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, Double.valueOf(numeric[0])); - - } - - // decimal(10,5) - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, new BigDecimal(numeric[1]), java.sql.Types.DECIMAL, precision, scale); - } - - // numeric(8,2) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, new BigDecimal(numeric[2]), java.sql.Types.NUMERIC, precision, scale); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // float(30) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, Double.valueOf(numeric[0])); + + } + + // decimal(10,5) + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, new BigDecimal(numeric[1]), java.sql.Types.DECIMAL, precision, scale); + } + + // numeric(8,2) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, new BigDecimal(numeric[2]), java.sql.Types.NUMERIC, precision, scale); + } + + pstmt.execute(); } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateNumericSetObjectNull(int precision, int scale) throws SQLException { String sql = "insert into " + numericTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // float(30) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.DOUBLE); - + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // float(30) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.DOUBLE); + + } + + // decimal(10,5) + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.DECIMAL, precision, scale); + } + + // numeric(8,2) + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, java.sql.Types.NUMERIC, precision, scale); + } + + pstmt.execute(); } - - // decimal(10,5) - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.DECIMAL, precision, scale); - } - - // numeric(8,2) - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, java.sql.Types.NUMERIC, precision, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateDateSetObject(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP, scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP); - } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP, scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, new Timestamp(date.getTime()), java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME, scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET, scale); + } + + pstmt.execute(); } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, new Time(date.getTime()), java.sql.Types.TIME, scale); - } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, microsoft.sql.DateTimeOffset.valueOf(new Timestamp(date.getTime()), 1), microsoft.sql.Types.DATETIMEOFFSET, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } private void populateDateSetObjectNull(int scale) throws SQLException { String sql = "insert into " + dateTable + " values( " + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?," + "?,?,?" + ")"; - pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting); - - // datetime2(5) - for (int i = 1; i <= 3; i++) { - pstmt.setObject(i, null, java.sql.Types.TIMESTAMP, scale); - } - - // datetime2 default - for (int i = 4; i <= 6; i++) { - pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + try(SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) Util.getPreparedStmt(con, sql, stmtColEncSetting)) { + + // datetime2(5) + for (int i = 1; i <= 3; i++) { + pstmt.setObject(i, null, java.sql.Types.TIMESTAMP, scale); + } + + // datetime2 default + for (int i = 4; i <= 6; i++) { + pstmt.setObject(i, null, java.sql.Types.TIMESTAMP); + } + + // datetimeoffset default + for (int i = 7; i <= 9; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); + } + + // time default + for (int i = 10; i <= 12; i++) { + pstmt.setObject(i, null, java.sql.Types.TIME); + } + + // time(3) + for (int i = 13; i <= 15; i++) { + pstmt.setObject(i, null, java.sql.Types.TIME, scale); + } + + // datetimeoffset(2) + for (int i = 16; i <= 18; i++) { + pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET, scale); + } + + pstmt.execute(); } - - // datetimeoffset default - for (int i = 7; i <= 9; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET); - } - - // time default - for (int i = 10; i <= 12; i++) { - pstmt.setObject(i, null, java.sql.Types.TIME); - } - - // time(3) - for (int i = 13; i <= 15; i++) { - pstmt.setObject(i, null, java.sql.Types.TIME, scale); - } - - // datetimeoffset(2) - for (int i = 16; i <= 18; i++) { - pstmt.setObject(i, null, microsoft.sql.Types.DATETIMEOFFSET, scale); - } - - pstmt.execute(); - Util.close(null, pstmt, null); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java index d97726b27..7782a86b7 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyAllTypes.java @@ -27,9 +27,7 @@ @RunWith(JUnitPlatform.class) public class BulkCopyAllTypes extends AbstractTest { - private static Connection conn = null; - static Statement stmt = null; - + private static DBTable tableSrc = null; private static DBTable tableDest = null; @@ -53,55 +51,43 @@ private void testBulkCopyResultSet(boolean setSelectMethod, Integer resultSetConcurrency) throws SQLException { setupVariation(); - Connection connnection = null; - if (setSelectMethod) { - connnection = DriverManager.getConnection(connectionString + ";selectMethod=cursor;"); - } - else { - connnection = DriverManager.getConnection(connectionString); - } - - Statement stmtement = null; - if (null != resultSetType || null != resultSetConcurrency) { - stmtement = connnection.createStatement(resultSetType, resultSetConcurrency); + try(Connection connnection = DriverManager.getConnection(connectionString + (setSelectMethod ? ";selectMethod=cursor;" : "")); + Statement statement = (null != resultSetType || null != resultSetConcurrency) ? + connnection.createStatement(resultSetType, resultSetConcurrency) : connnection.createStatement()){ + + ResultSet rs = statement.executeQuery("select * from " + tableSrc.getEscapedTableName()); + + SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connection); + bcOperation.setDestinationTableName(tableDest.getEscapedTableName()); + bcOperation.writeToServer(rs); + bcOperation.close(); + + ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, tableDest); } - else { - stmtement = connnection.createStatement(); - } - - ResultSet rs = stmtement.executeQuery("select * from " + tableSrc.getEscapedTableName()); - - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connection); - bcOperation.setDestinationTableName(tableDest.getEscapedTableName()); - bcOperation.writeToServer(rs); - bcOperation.close(); - - ComparisonUtil.compareSrcTableAndDestTableIgnoreRowOrder(new DBConnection(connectionString), tableSrc, tableDest); terminateVariation(); } private void setupVariation() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - - DBConnection dbConnection = new DBConnection(connectionString); - DBStatement dbStmt = dbConnection.createStatement(); - - tableSrc = new DBTable(true); - tableDest = tableSrc.cloneSchema(); - - dbStmt.createTable(tableSrc); - dbStmt.createTable(tableDest); - - dbStmt.populateTable(tableSrc); + try(DBConnection dbConnection = new DBConnection(connectionString); + DBStatement dbStmt = dbConnection.createStatement()) { + + tableSrc = new DBTable(true); + tableDest = tableSrc.cloneSchema(); + + dbStmt.createTable(tableSrc); + dbStmt.createTable(tableDest); + + dbStmt.populateTable(tableSrc); + } } private void terminateVariation() throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); + try(Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { - Utils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); - Utils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); + Utils.dropTableIfExists(tableSrc.getEscapedTableName(), stmt); + Utils.dropTableIfExists(tableDest.getEscapedTableName(), stmt); + } } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java index c915ad594..ebf311225 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyCSVTest.java @@ -77,9 +77,7 @@ static void setUpConnection() { @Test @DisplayName("Test SQLServerBulkCSVFileRecord") void testCSV() { - SQLServerBulkCSVFileRecord fileRecord; - try { - fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFile, encoding, delimiter, true); + try (SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFile, encoding, delimiter, true)) { testBulkCopyCSV(fileRecord, true); } catch (SQLServerException e) { @@ -93,9 +91,7 @@ void testCSV() { @Test @DisplayName("Test SQLServerBulkCSVFileRecord First line not being column name") void testCSVFirstLineNotColumnName() { - SQLServerBulkCSVFileRecord fileRecord; - try { - fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFileNoColumnName, encoding, delimiter, false); + try (SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(filePath + inputFileNoColumnName, encoding, delimiter, false)) { testBulkCopyCSV(fileRecord, false); } catch (SQLServerException e) { @@ -111,10 +107,9 @@ void testCSVFirstLineNotColumnName() { @Test @DisplayName("Test SQLServerBulkCSVFileRecord with passing file from url") void testCSVFromURL() throws SQLException { - try { - InputStream csvFileInputStream = new URL( + try (InputStream csvFileInputStream = new URL( "https://raw.githubusercontent.com/Microsoft/mssql-jdbc/master/src/test/resources/BulkCopyCSVTestInput.csv").openStream(); - SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(csvFileInputStream, encoding, delimiter, true); + SQLServerBulkCSVFileRecord fileRecord = new SQLServerBulkCSVFileRecord(csvFileInputStream, encoding, delimiter, true)) { testBulkCopyCSV(fileRecord, true); } catch (Exception e) { @@ -125,53 +120,52 @@ void testCSVFromURL() throws SQLException { private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, boolean firstLineIsColumnNames) { DBTable destTable = null; - try { - BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding)); + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding))) { // read the first line from csv and parse it to get datatypes to create destination column String[] columnTypes = br.readLine().substring(1)/* Skip the Byte order mark */.split(delimiter, -1); br.close(); int numberOfColumns = columnTypes.length; destTable = new DBTable(false); - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - bulkCopy.setDestinationTableName(destTable.getEscapedTableName()); - - // add a column in destTable for each datatype in csv - for (int i = 0; i < numberOfColumns; i++) { - SqlType sqlType = null; - int precision = -1; - int scale = -1; - - String columnType = columnTypes[i].trim().toLowerCase(); - int indexOpenParenthesis = columnType.lastIndexOf("("); - // skip the parenthesis in case of precision and scale type - if (-1 != indexOpenParenthesis) { - String precision_scale = columnType.substring(indexOpenParenthesis + 1, columnType.length() - 1); - columnType = columnType.substring(0, indexOpenParenthesis); - sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; - - // add scale if exist - int indexPrecisionScaleSeparator = precision_scale.indexOf("-"); - if (-1 != indexPrecisionScaleSeparator) { - scale = Integer.parseInt(precision_scale.substring(indexPrecisionScaleSeparator + 1)); - sqlType.setScale(scale); - precision_scale = precision_scale.substring(0, indexPrecisionScaleSeparator); - } - // add precision - precision = Integer.parseInt(precision_scale); - sqlType.setPrecision(precision); - } - else { - sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; - } - - destTable.addColumn(sqlType); - fileRecord.addColumnMetadata(i + 1, "", sqlType.getJdbctype().getVendorTypeNumber(), (-1 == precision) ? 0 : precision, - (-1 == scale) ? 0 : scale); + try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy((Connection) con.product())) { + bulkCopy.setDestinationTableName(destTable.getEscapedTableName()); + + // add a column in destTable for each datatype in csv + for (int i = 0; i < numberOfColumns; i++) { + SqlType sqlType = null; + int precision = -1; + int scale = -1; + + String columnType = columnTypes[i].trim().toLowerCase(); + int indexOpenParenthesis = columnType.lastIndexOf("("); + // skip the parenthesis in case of precision and scale type + if (-1 != indexOpenParenthesis) { + String precision_scale = columnType.substring(indexOpenParenthesis + 1, columnType.length() - 1); + columnType = columnType.substring(0, indexOpenParenthesis); + sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; + + // add scale if exist + int indexPrecisionScaleSeparator = precision_scale.indexOf("-"); + if (-1 != indexPrecisionScaleSeparator) { + scale = Integer.parseInt(precision_scale.substring(indexPrecisionScaleSeparator + 1)); + sqlType.setScale(scale); + precision_scale = precision_scale.substring(0, indexPrecisionScaleSeparator); + } + // add precision + precision = Integer.parseInt(precision_scale); + sqlType.setPrecision(precision); + } + else { + sqlType = SqlTypeMapping.valueOf(columnType.toUpperCase()).sqlType; + } + + destTable.addColumn(sqlType); + fileRecord.addColumnMetadata(i + 1, "", sqlType.getJdbctype().getVendorTypeNumber(), (-1 == precision) ? 0 : precision, + (-1 == scale) ? 0 : scale); + } + stmt.createTable(destTable); + bulkCopy.writeToServer((ISQLServerBulkRecord) fileRecord); } - stmt.createTable(destTable); - bulkCopy.writeToServer((ISQLServerBulkRecord) fileRecord); - bulkCopy.close(); if (firstLineIsColumnNames) validateValuesFromCSV(destTable, inputFile); else @@ -186,7 +180,6 @@ private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, stmt.dropTable(destTable); } } - } /** @@ -196,30 +189,28 @@ private void testBulkCopyCSV(SQLServerBulkCSVFileRecord fileRecord, */ static void validateValuesFromCSV(DBTable destinationTable, String inputFile) { - BufferedReader br; - try { - br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding)); + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + inputFile), encoding))) { if (inputFile.equalsIgnoreCase("BulkCopyCSVTestInput.csv")) br.readLine(); // skip first line as it is header - DBResultSet dstResultSet = stmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); - int totalColumns = destMeta.getColumnCount(); - while (dstResultSet.next()) { - String[] srcValues = br.readLine().split(delimiter); - if ((0 == srcValues.length) && (srcValues.length != totalColumns)) { - srcValues = new String[totalColumns]; - Arrays.fill(srcValues, null); - } - for (int i = 1; i <= totalColumns; i++) { - String srcValue = srcValues[i - 1]; - String dstValue = dstResultSet.getString(i); - srcValue = (null != srcValue) ? srcValue.trim() : srcValue; - dstValue = (null != dstValue) ? dstValue.trim() : dstValue; - - // get the value from csv as string and compare them - ComparisonUtil.compareExpectedAndActual(java.sql.Types.VARCHAR, srcValue, dstValue); - } + try (DBResultSet dstResultSet = stmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); + int totalColumns = destMeta.getColumnCount(); + while (dstResultSet.next()) { + String[] srcValues = br.readLine().split(delimiter); + if ((0 == srcValues.length) && (srcValues.length != totalColumns)) { + srcValues = new String[totalColumns]; + Arrays.fill(srcValues, null); + } + for (int i = 1; i <= totalColumns; i++) { + String srcValue = srcValues[i - 1]; + String dstValue = dstResultSet.getString(i); + srcValue = (null != srcValue) ? srcValue.trim() : srcValue; + dstValue = (null != dstValue) ? dstValue.trim() : dstValue; + // get the value from csv as string and compare them + ComparisonUtil.compareExpectedAndActual(java.sql.Types.VARCHAR, srcValue, dstValue); + } + } } } catch (Exception e) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java index 22570060a..2de49b360 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyColumnMappingTest.java @@ -332,31 +332,32 @@ void testInvalidCM() { private void validateValuesRepetativeCM(DBConnection con, DBTable sourceTable, DBTable destinationTable) throws SQLException { - DBStatement srcStmt = con.createStatement(); - DBStatement dstStmt = con.createStatement(); - DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData sourceMeta = ((ResultSet) srcResultSet.product()).getMetaData(); - int totalColumns = sourceMeta.getColumnCount(); - - // verify data from sourceType and resultSet - while (srcResultSet.next() && dstResultSet.next()) - for (int i = 1; i <= totalColumns; i++) { - // TODO: check row and column count in both the tables - - Object srcValue, dstValue; - srcValue = srcResultSet.getObject(i); - dstValue = dstResultSet.getObject(i); - ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValue, dstValue); - - // compare value of first column of source with extra column in destination - if (1 == i) { - Object srcValueFirstCol = srcResultSet.getObject(i); - Object dstValLastCol = dstResultSet.getObject(totalColumns + 1); - ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValueFirstCol, dstValLastCol); - } - } - + try(DBStatement srcStmt = con.createStatement(); + DBStatement dstStmt = con.createStatement(); + DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData sourceMeta = ((ResultSet) srcResultSet.product()).getMetaData(); + int totalColumns = sourceMeta.getColumnCount(); + + // verify data from sourceType and resultSet + while (srcResultSet.next() && dstResultSet.next()) { + for (int i = 1; i <= totalColumns; i++) { + // TODO: check row and column count in both the tables + + Object srcValue, dstValue; + srcValue = srcResultSet.getObject(i); + dstValue = dstResultSet.getObject(i); + ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValue, dstValue); + + // compare value of first column of source with extra column in destination + if (1 == i) { + Object srcValueFirstCol = srcResultSet.getObject(i); + Object dstValLastCol = dstResultSet.getObject(totalColumns + 1); + ComparisonUtil.compareExpectedAndActual(sourceMeta.getColumnType(i), srcValueFirstCol, dstValLastCol); + } + } + } + } } private void dropTable(String tableName) { diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java index 340dbb3eb..f56039813 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyConnectionTest.java @@ -12,6 +12,7 @@ import java.lang.reflect.Method; import java.sql.Connection; +import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; @@ -88,9 +89,11 @@ public void execute() { void testInvalidConnection1() { assertThrows(SQLServerException.class, new org.junit.jupiter.api.function.Executable() { @Override - public void execute() throws SQLServerException { - Connection con = null; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + public void execute() throws SQLException { + try(Connection con = null; + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con)) { + //do nothing + } } }); } @@ -104,8 +107,10 @@ void testInvalidConnection2() { assertThrows(SQLServerException.class, new org.junit.jupiter.api.function.Executable() { @Override public void execute() throws SQLServerException { - SQLServerConnection con = null; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con); + try(SQLServerConnection con = null; + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(con)) { + //do nothing + } } }); } @@ -120,7 +125,9 @@ void testInvalidConnection3() { @Override public void execute() throws SQLServerException { String connectionUrl = " "; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl); + try(SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl)) { + //do nothing + } } }); } @@ -135,7 +142,9 @@ void testInvalidConnection4() { @Override public void execute() throws SQLServerException { String connectionUrl = null; - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl); + try(SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(connectionUrl)) { + //do nothing + } } }); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java index 60e7e3da4..1be4ad850 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyISQLServerBulkRecordTest.java @@ -38,39 +38,18 @@ @DisplayName("Test ISQLServerBulkRecord") public class BulkCopyISQLServerBulkRecordTest extends AbstractTest { - static DBConnection con = null; - static DBStatement stmt = null; - static DBTable dstTable = null; - - /** - * Create connection and statement - */ - @BeforeAll - static void setUpConnection() { - con = new DBConnection(connectionString); - stmt = con.createStatement(); - } - @Test - void testISQLServerBulkRecord() { - dstTable = new DBTable(true); - stmt.createTable(dstTable); - BulkData Bdata = new BulkData(); - - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, Bdata, dstTable); - } - - /** - * drop source table after testing bulk copy - * - * @throws SQLException - */ - @AfterAll - static void tearConnection() throws SQLException { - stmt.close(); - con.close(); + void testISQLServerBulkRecord() throws SQLException { + try (DBConnection con = new DBConnection(connectionString); + DBStatement stmt = con.createStatement()) { + DBTable dstTable = new DBTable(true); + stmt.createTable(dstTable); + BulkData Bdata = new BulkData(dstTable); + + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, Bdata, dstTable); + } } class BulkData implements ISQLServerBulkRecord { @@ -98,7 +77,7 @@ private class ColumnMetadata { Map columnMetadata; List data; - BulkData() { + BulkData(DBTable dstTable) { columnMetadata = new HashMap<>(); totalColumn = dstTable.totalColumns(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java index eeaad7577..774deff4a 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyResultSetCursorTest.java @@ -20,7 +20,6 @@ import java.util.Properties; import java.util.TimeZone; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @@ -33,9 +32,6 @@ @RunWith(JUnitPlatform.class) public class BulkCopyResultSetCursorTest extends AbstractTest { - private static Connection conn = null; - static Statement stmt = null; - static BigDecimal[] expectedBigDecimals = {new BigDecimal("12345.12345"), new BigDecimal("125.123"), new BigDecimal("45.12345")}; static String[] expectedBigDecimalStrings = {"12345.12345", "125.12300", "45.12345"}; @@ -62,27 +58,20 @@ public void testServerCursors() throws SQLException { private void serverCursorsTest(int resultSetType, int resultSetConcurrency) throws SQLException { - conn = DriverManager.getConnection(connectionString); - stmt = conn.createStatement(); - - dropTables(); - createTables(); - - populateSourceTable(); - - ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency).executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn); - bulkCopy.setDestinationTableName(desTable); - bulkCopy.writeToServer(rs); - - verifyDestinationTableData(expectedBigDecimals.length); - - if (null != bulkCopy) { - bulkCopy.close(); - } - if (null != rs) { - rs.close(); + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + + dropTables(stmt); + createTables(stmt); + populateSourceTable(); + + try (ResultSet rs = conn.createStatement(resultSetType, resultSetConcurrency).executeQuery("select * from " + srcTable); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); + bulkCopy.writeToServer(rs); + + verifyDestinationTableData(expectedBigDecimals.length); + } } } @@ -95,28 +84,19 @@ private void serverCursorsTest(int resultSetType, public void testSelectMethodSetToCursor() throws SQLException { Properties info = new Properties(); info.setProperty("SelectMethod", "cursor"); - conn = DriverManager.getConnection(connectionString, info); - - stmt = conn.createStatement(); - - dropTables(); - createTables(); - - populateSourceTable(); - - ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn); - bulkCopy.setDestinationTableName(desTable); - bulkCopy.writeToServer(rs); - - verifyDestinationTableData(expectedBigDecimals.length); - - if (null != bulkCopy) { - bulkCopy.close(); - } - if (null != rs) { - rs.close(); + try (Connection conn = DriverManager.getConnection(connectionString, info); + Statement stmt = conn.createStatement()) { + dropTables(stmt); + createTables(stmt); + populateSourceTable(); + + try (ResultSet rs = conn.createStatement().executeQuery("select * from " + srcTable); + SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); + bulkCopy.writeToServer(rs); + + verifyDestinationTableData(expectedBigDecimals.length); + } } } @@ -127,133 +107,106 @@ public void testSelectMethodSetToCursor() throws SQLException { */ @Test public void testMultiplePreparedStatementAndResultSet() throws SQLException { - conn = DriverManager.getConnection(connectionString); - - stmt = conn.createStatement(); - - dropTables(); - createTables(); - - populateSourceTable(); - - ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn); - bulkCopy.setDestinationTableName(desTable); - bulkCopy.writeToServer(rs); - verifyDestinationTableData(expectedBigDecimals.length); - - rs.beforeFirst(); - SQLServerBulkCopy bulkCopy1 = new SQLServerBulkCopy(conn); - bulkCopy1.setDestinationTableName(desTable); - bulkCopy1.writeToServer(rs); - verifyDestinationTableData(expectedBigDecimals.length * 2); - - rs.beforeFirst(); - SQLServerBulkCopy bulkCopy2 = new SQLServerBulkCopy(conn); - bulkCopy2.setDestinationTableName(desTable); - bulkCopy2.writeToServer(rs); - verifyDestinationTableData(expectedBigDecimals.length * 3); - - String sql = "insert into " + desTable + " values (?,?,?,?)"; - Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - SQLServerPreparedStatement pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement(sql); - for (int i = 0; i < expectedBigDecimals.length; i++) { - pstmt1.setBigDecimal(1, expectedBigDecimals[i]); - pstmt1.setString(2, expectedStrings[i]); - pstmt1.setTimestamp(3, expectedTimestamps[i], calGMT); - pstmt1.setString(4, expectedStrings[i]); - pstmt1.execute(); - } - verifyDestinationTableData(expectedBigDecimals.length * 4); - - ResultSet rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable); - - SQLServerBulkCopy bulkCopy3 = new SQLServerBulkCopy(conn); - bulkCopy3.setDestinationTableName(desTable); - bulkCopy3.writeToServer(rs2); - verifyDestinationTableData(expectedBigDecimals.length * 5); - - if (null != pstmt1) { - pstmt1.close(); - } - if (null != bulkCopy) { - bulkCopy.close(); - } - if (null != bulkCopy1) { - bulkCopy1.close(); - } - if (null != bulkCopy2) { - bulkCopy2.close(); - } - if (null != bulkCopy3) { - bulkCopy3.close(); - } - if (null != rs) { - rs.close(); - } - if (null != rs2) { - rs2.close(); - } + try (Connection conn = DriverManager.getConnection(connectionString); + Statement stmt = conn.createStatement()) { + + dropTables(stmt); + createTables(stmt); + populateSourceTable(); + + try (ResultSet rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable)) { + try (SQLServerBulkCopy bulkCopy = new SQLServerBulkCopy(conn)) { + bulkCopy.setDestinationTableName(desTable); + bulkCopy.writeToServer(rs); + verifyDestinationTableData(expectedBigDecimals.length); + } + + rs.beforeFirst(); + try (SQLServerBulkCopy bulkCopy1 = new SQLServerBulkCopy(conn)) { + bulkCopy1.setDestinationTableName(desTable); + bulkCopy1.writeToServer(rs); + verifyDestinationTableData(expectedBigDecimals.length * 2); + } + + rs.beforeFirst(); + try (SQLServerBulkCopy bulkCopy2 = new SQLServerBulkCopy(conn)) { + bulkCopy2.setDestinationTableName(desTable); + bulkCopy2.writeToServer(rs); + verifyDestinationTableData(expectedBigDecimals.length * 3); + } + + String sql = "insert into " + desTable + " values (?,?,?,?)"; + Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + try (SQLServerPreparedStatement pstmt1 = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { + for (int i = 0; i < expectedBigDecimals.length; i++) { + pstmt1.setBigDecimal(1, expectedBigDecimals[i]); + pstmt1.setString(2, expectedStrings[i]); + pstmt1.setTimestamp(3, expectedTimestamps[i], calGMT); + pstmt1.setString(4, expectedStrings[i]); + pstmt1.execute(); + } + verifyDestinationTableData(expectedBigDecimals.length * 4); + } + try (ResultSet rs2 = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE).executeQuery("select * from " + srcTable); + SQLServerBulkCopy bulkCopy3 = new SQLServerBulkCopy(conn)) { + bulkCopy3.setDestinationTableName(desTable); + bulkCopy3.writeToServer(rs2); + verifyDestinationTableData(expectedBigDecimals.length * 5); + } + } + } } private static void verifyDestinationTableData(int expectedNumberOfRows) throws SQLException { - ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable); - - int expectedArrayLength = expectedBigDecimals.length; - - int i = 0; - while (rs.next()) { - assertTrue(rs.getString(1).equals(expectedBigDecimalStrings[i % expectedArrayLength]), - "Expected Value:" + expectedBigDecimalStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(1)); - assertTrue(rs.getString(2).trim().equals(expectedStrings[i % expectedArrayLength]), - "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(2)); - assertTrue(rs.getString(3).equals(expectedTimestampStrings[i % expectedArrayLength]), - "Expected Value:" + expectedTimestampStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(3)); - assertTrue(rs.getString(4).trim().equals(expectedStrings[i % expectedArrayLength]), - "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(4)); - i++; + try (Connection conn = DriverManager.getConnection(connectionString); + ResultSet rs = conn.createStatement().executeQuery("select * from " + desTable)) { + + int expectedArrayLength = expectedBigDecimals.length; + + int i = 0; + while (rs.next()) { + assertTrue(rs.getString(1).equals(expectedBigDecimalStrings[i % expectedArrayLength]), + "Expected Value:" + expectedBigDecimalStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(1)); + assertTrue(rs.getString(2).trim().equals(expectedStrings[i % expectedArrayLength]), + "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(2)); + assertTrue(rs.getString(3).equals(expectedTimestampStrings[i % expectedArrayLength]), + "Expected Value:" + expectedTimestampStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(3)); + assertTrue(rs.getString(4).trim().equals(expectedStrings[i % expectedArrayLength]), + "Expected Value:" + expectedStrings[i % expectedArrayLength] + ", Actual Value: " + rs.getString(4)); + i++; + } + + assertTrue(i == expectedNumberOfRows); } - - assertTrue(i == expectedNumberOfRows); } private static void populateSourceTable() throws SQLException { String sql = "insert into " + srcTable + " values (?,?,?,?)"; - Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql); + try (Connection conn = DriverManager.getConnection(connectionString); + SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement) conn.prepareStatement(sql)) { - for (int i = 0; i < expectedBigDecimals.length; i++) { - pstmt.setBigDecimal(1, expectedBigDecimals[i]); - pstmt.setString(2, expectedStrings[i]); - pstmt.setTimestamp(3, expectedTimestamps[i], calGMT); - pstmt.setString(4, expectedStrings[i]); - pstmt.execute(); + for (int i = 0; i < expectedBigDecimals.length; i++) { + pstmt.setBigDecimal(1, expectedBigDecimals[i]); + pstmt.setString(2, expectedStrings[i]); + pstmt.setTimestamp(3, expectedTimestamps[i], calGMT); + pstmt.setString(4, expectedStrings[i]); + pstmt.execute(); + } } } - private static void dropTables() throws SQLException { + private static void dropTables(Statement stmt) throws SQLException { Utils.dropTableIfExists(srcTable, stmt); Utils.dropTableIfExists(desTable, stmt); } - private static void createTables() throws SQLException { + private static void createTables(Statement stmt) throws SQLException { String sql = "create table " + srcTable + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); sql = "create table " + desTable + " (c1 decimal(10,5) null, c2 nchar(50) null, c3 datetime2(7) null, c4 char(7000));"; stmt.execute(sql); } - - @AfterEach - private void terminateVariation() throws SQLException { - if (null != conn) { - conn.close(); - } - if (null != stmt) { - stmt.close(); - } - } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java index 2b23bf836..f916336de 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestSetUp.java @@ -7,6 +7,8 @@ */ package com.microsoft.sqlserver.jdbc.bulkCopy; +import java.sql.SQLException; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.platform.runner.JUnitPlatform; @@ -28,39 +30,28 @@ public class BulkCopyTestSetUp extends AbstractTest { /** * Create source table needed for testing bulk copy + * @throws SQLException */ @BeforeAll - static void setUpSourceTable() { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(connectionString); - stmt = con.createStatement(); + static void setUpSourceTable() throws SQLException { + try (DBConnection con = new DBConnection(connectionString); + DBStatement stmt = con.createStatement(); + DBPreparedStatement pstmt = new DBPreparedStatement(con);) { sourceTable = new DBTable(true); stmt.createTable(sourceTable); - DBPreparedStatement pstmt = new DBPreparedStatement(con); pstmt.populateTable(sourceTable); } - finally { - con.close(); - } } /** * drop source table after testing bulk copy + * @throws SQLException */ @AfterAll - static void dropSourceTable() { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(connectionString); - stmt = con.createStatement(); + static void dropSourceTable() throws SQLException { + try (DBConnection con = new DBConnection(connectionString); + DBStatement stmt = con.createStatement()) { stmt.dropTable(sourceTable); } - finally { - con.close(); - } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java index fd51ef544..0b902587e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTestUtil.java @@ -7,20 +7,12 @@ */ package com.microsoft.sqlserver.jdbc.bulkCopy; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.math.BigDecimal; import java.sql.Connection; -import java.sql.Date; -import java.sql.JDBCType; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; -import java.sql.Time; -import java.sql.Timestamp; - import com.microsoft.sqlserver.jdbc.ISQLServerBulkRecord; import com.microsoft.sqlserver.jdbc.SQLServerBulkCopy; import com.microsoft.sqlserver.jdbc.bulkCopy.BulkCopyTestWrapper.ColumnMap; @@ -28,7 +20,6 @@ import com.microsoft.sqlserver.testframework.DBResultSet; import com.microsoft.sqlserver.testframework.DBStatement; import com.microsoft.sqlserver.testframework.DBTable; -import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.util.ComparisonUtil; /** @@ -70,57 +61,53 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, boolean validateResult) { - DBConnection con = null; - DBStatement stmt = null; DBTable destinationTable = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement()) { destinationTable = sourceTable.cloneSchema(); stmt.createTable(destinationTable); - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); + try (DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { + if (wrapper.isUsingBulkCopyOptions()) { + bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); + } + bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); + if (wrapper.isUsingColumnMapping()) { + for (int i = 0; i < wrapper.cm.size(); i++) { + ColumnMap currentMap = wrapper.cm.get(i); + if (currentMap.sourceIsInt && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); + } + else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); + } + else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); + } + else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); + } + } + } + bulkCopy.writeToServer((ResultSet) srcResultSet.product()); + if (validateResult) { + validateValues(con, sourceTable, destinationTable); + } } - if (wrapper.isUsingBulkCopyOptions()) { - bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); - } - bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); - if (wrapper.isUsingColumnMapping()) { - for (int i = 0; i < wrapper.cm.size(); i++) { - ColumnMap currentMap = wrapper.cm.get(i); - if (currentMap.sourceIsInt && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); - } - else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); - } - else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); - } - else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); - } - } + catch (SQLException ex) { + fail(ex.getMessage()); } - bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - bulkCopy.close(); - if (validateResult) { - validateValues(con, sourceTable, destinationTable); + finally { + stmt.dropTable(destinationTable); + con.close(); } } catch (SQLException ex) { fail(ex.getMessage()); } - finally { - stmt.dropTable(destinationTable); - con.close(); - } } /** @@ -135,20 +122,12 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable sourceTable, DBTable destinationTable, boolean validateResult) { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); - - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); - } + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { if (wrapper.isUsingBulkCopyOptions()) { bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); } @@ -171,18 +150,13 @@ else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { } } bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - bulkCopy.close(); if (validateResult) { validateValues(con, sourceTable, destinationTable); } - } + } catch (SQLException ex) { fail(ex.getMessage()); } - finally { - stmt.dropTable(destinationTable); - con.close(); - } } /** @@ -199,58 +173,54 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, DBTable destinationTable, boolean validateResult, boolean fail) { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); - - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); - } - if (wrapper.isUsingBulkCopyOptions()) { - bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); - } - bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); - if (wrapper.isUsingColumnMapping()) { - for (int i = 0; i < wrapper.cm.size(); i++) { - ColumnMap currentMap = wrapper.cm.get(i); - if (currentMap.sourceIsInt && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); - } - else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); - } - else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); - } - else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); - } - } - } - bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - if (fail) - fail("bulkCopy.writeToServer did not fail when it should have"); - bulkCopy.close(); - if (validateResult) { - validateValues(con, sourceTable, destinationTable); - } - } - catch (SQLException ex) { + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { + try { + if (wrapper.isUsingBulkCopyOptions()) { + bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); + } + bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); + if (wrapper.isUsingColumnMapping()) { + for (int i = 0; i < wrapper.cm.size(); i++) { + ColumnMap currentMap = wrapper.cm.get(i); + if (currentMap.sourceIsInt && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); + } + else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); + } + else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); + } + else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); + } + } + } + bulkCopy.writeToServer((ResultSet) srcResultSet.product()); + if (fail) + fail("bulkCopy.writeToServer did not fail when it should have"); + if (validateResult) { + validateValues(con, sourceTable, destinationTable); + } + } catch (SQLException ex) { + if (!fail) { + fail(ex.getMessage()); + } + } + finally { + stmt.dropTable(destinationTable); + con.close(); + } + } catch (SQLException e) { if (!fail) { - fail(ex.getMessage()); + fail(e.getMessage()); } - } - finally { - stmt.dropTable(destinationTable); - con.close(); - } + } } /** @@ -269,60 +239,59 @@ static void performBulkCopy(BulkCopyTestWrapper wrapper, boolean validateResult, boolean fail, boolean dropDest) { - DBConnection con = null; - DBStatement stmt = null; - try { - con = new DBConnection(wrapper.getConnectionString()); - stmt = con.createStatement(); - - DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - SQLServerBulkCopy bulkCopy; - if (wrapper.isUsingConnection()) { - bulkCopy = new SQLServerBulkCopy((Connection) con.product()); - } - else { - bulkCopy = new SQLServerBulkCopy(wrapper.getConnectionString()); - } - if (wrapper.isUsingBulkCopyOptions()) { - bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); - } - bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); - if (wrapper.isUsingColumnMapping()) { - for (int i = 0; i < wrapper.cm.size(); i++) { - ColumnMap currentMap = wrapper.cm.get(i); - if (currentMap.sourceIsInt && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); - } - else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); - } - else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); - } - else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { - bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); - } - } - } - bulkCopy.writeToServer((ResultSet) srcResultSet.product()); - if (fail) - fail("bulkCopy.writeToServer did not fail when it should have"); - bulkCopy.close(); - if (validateResult) { - validateValues(con, sourceTable, destinationTable); - } + try (DBConnection con = new DBConnection(wrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + DBResultSet srcResultSet = stmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + SQLServerBulkCopy bulkCopy = wrapper.isUsingConnection() ? + new SQLServerBulkCopy((Connection) con.product()) : + new SQLServerBulkCopy(wrapper.getConnectionString())) { + try { + if (wrapper.isUsingBulkCopyOptions()) { + bulkCopy.setBulkCopyOptions(wrapper.getBulkOptions()); + } + bulkCopy.setDestinationTableName(destinationTable.getEscapedTableName()); + if (wrapper.isUsingColumnMapping()) { + for (int i = 0; i < wrapper.cm.size(); i++) { + ColumnMap currentMap = wrapper.cm.get(i); + if (currentMap.sourceIsInt && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destInt); + } + else if (currentMap.sourceIsInt && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcInt, currentMap.destString); + } + else if ((!currentMap.sourceIsInt) && currentMap.destIsInt) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destInt); + } + else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { + bulkCopy.addColumnMapping(currentMap.srcString, currentMap.destString); + } + } + } + bulkCopy.writeToServer((ResultSet) srcResultSet.product()); + if (fail) + fail("bulkCopy.writeToServer did not fail when it should have"); + bulkCopy.close(); + if (validateResult) { + validateValues(con, sourceTable, destinationTable); + } + } + catch (SQLException ex) { + if (!fail) { + fail(ex.getMessage()); + } + } + finally { + if (dropDest) { + stmt.dropTable(destinationTable); + } + con.close(); + } } catch (SQLException ex) { if (!fail) { fail(ex.getMessage()); } } - finally { - if (dropDest) { - stmt.dropTable(destinationTable); - } - con.close(); - } } /** @@ -336,24 +305,26 @@ else if ((!currentMap.sourceIsInt) && (!currentMap.destIsInt)) { static void validateValues(DBConnection con, DBTable sourceTable, DBTable destinationTable) throws SQLException { - DBStatement srcStmt = con.createStatement(); - DBStatement dstStmt = con.createStatement(); - DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); - DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); - int totalColumns = destMeta.getColumnCount(); - - // verify data from sourceType and resultSet - while (srcResultSet.next() && dstResultSet.next()) - for (int i = 1; i <= totalColumns; i++) { - // TODO: check row and column count in both the tables - - Object srcValue, dstValue; - srcValue = srcResultSet.getObject(i); - dstValue = dstResultSet.getObject(i); - - ComparisonUtil.compareExpectedAndActual(destMeta.getColumnType(i), srcValue, dstValue); - } + try (DBStatement srcStmt = con.createStatement(); + DBStatement dstStmt = con.createStatement(); + DBResultSet srcResultSet = srcStmt.executeQuery("SELECT * FROM " + sourceTable.getEscapedTableName() + ";"); + DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); + int totalColumns = destMeta.getColumnCount(); + + // verify data from sourceType and resultSet + while (srcResultSet.next() && dstResultSet.next()) { + for (int i = 1; i <= totalColumns; i++) { + // TODO: check row and column count in both the tables + + Object srcValue, dstValue; + srcValue = srcResultSet.getObject(i); + dstValue = dstResultSet.getObject(i); + + ComparisonUtil.compareExpectedAndActual(destMeta.getColumnType(i), srcValue, dstValue); + } + } + } } /** @@ -365,22 +336,16 @@ static void validateValues(DBConnection con, static void performBulkCopy(BulkCopyTestWrapper bulkWrapper, ISQLServerBulkRecord srcData, DBTable dstTable) { - SQLServerBulkCopy bc; - DBConnection con = new DBConnection(bulkWrapper.getConnectionString()); - DBStatement stmt = con.createStatement(); - try { - bc = new SQLServerBulkCopy(bulkWrapper.getConnectionString()); + try (DBConnection con = new DBConnection(bulkWrapper.getConnectionString()); + DBStatement stmt = con.createStatement(); + SQLServerBulkCopy bc = new SQLServerBulkCopy(bulkWrapper.getConnectionString());) { bc.setDestinationTableName(dstTable.getEscapedTableName()); bc.writeToServer(srcData); - bc.close(); validateValues(con, srcData, dstTable); } catch (Exception e) { fail(e.getMessage()); } - finally { - con.close(); - } } /** @@ -395,38 +360,38 @@ static void validateValues( ISQLServerBulkRecord srcData, DBTable destinationTable) throws Exception { - DBStatement dstStmt = con.createStatement(); - DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";"); - ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); - int totalColumns = destMeta.getColumnCount(); - - // reset the counter in ISQLServerBulkRecord, which was incremented during read by BulkCopy - java.lang.reflect.Method method = srcData.getClass().getMethod("reset"); - method.invoke(srcData); - - - // verify data from sourceType and resultSet - while (srcData.next() && dstResultSet.next()) - { - Object[] srcValues = srcData.getRowData(); - for (int i = 1; i <= totalColumns; i++) { - - Object srcValue, dstValue; - srcValue = srcValues[i-1]; - if(srcValue.getClass().getName().equalsIgnoreCase("java.lang.Double")){ - // in case of SQL Server type Float (ie java type double), in float(n) if n is <=24 ie precsion is <=7 SQL Server type Real is returned(ie java type float) - if(destMeta.getPrecision(i) <8) - srcValue = new Float(((Double)srcValue)); - } - dstValue = dstResultSet.getObject(i); - int dstType = destMeta.getColumnType(i); - if(java.sql.Types.TIMESTAMP != dstType - && java.sql.Types.TIME != dstType - && microsoft.sql.Types.DATETIMEOFFSET != dstType){ - // skip validation for temporal types due to rounding eg 7986-10-21 09:51:15.114 is rounded as 7986-10-21 09:51:15.113 in server - ComparisonUtil.compareExpectedAndActual(dstType, srcValue, dstValue); - } - } + try (DBStatement dstStmt = con.createStatement(); + DBResultSet dstResultSet = dstStmt.executeQuery("SELECT * FROM " + destinationTable.getEscapedTableName() + ";")) { + ResultSetMetaData destMeta = ((ResultSet) dstResultSet.product()).getMetaData(); + int totalColumns = destMeta.getColumnCount(); + + // reset the counter in ISQLServerBulkRecord, which was incremented during read by BulkCopy + java.lang.reflect.Method method = srcData.getClass().getMethod("reset"); + method.invoke(srcData); + + // verify data from sourceType and resultSet + while (srcData.next() && dstResultSet.next()) + { + Object[] srcValues = srcData.getRowData(); + for (int i = 1; i <= totalColumns; i++) { + + Object srcValue, dstValue; + srcValue = srcValues[i-1]; + if(srcValue.getClass().getName().equalsIgnoreCase("java.lang.Double")){ + // in case of SQL Server type Float (ie java type double), in float(n) if n is <=24 ie precsion is <=7 SQL Server type Real is returned(ie java type float) + if(destMeta.getPrecision(i) <8) + srcValue = new Float(((Double)srcValue)); + } + dstValue = dstResultSet.getObject(i); + int dstType = destMeta.getColumnType(i); + if(java.sql.Types.TIMESTAMP != dstType + && java.sql.Types.TIME != dstType + && microsoft.sql.Types.DATETIMEOFFSET != dstType){ + // skip validation for temporal types due to rounding eg 7986-10-21 09:51:15.114 is rounded as 7986-10-21 09:51:15.113 in server + ComparisonUtil.compareExpectedAndActual(dstType, srcValue, dstValue); + } + } + } } } } \ No newline at end of file diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java index a2f5bdaac..3773e75fa 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/BulkCopyTimeoutTest.java @@ -38,13 +38,7 @@ public class BulkCopyTimeoutTest extends BulkCopyTestSetUp { @Test @DisplayName("BulkCopy:test zero timeout") void testZeroTimeOut() throws SQLServerException { - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); - option.setBulkCopyTimeout(0); - bulkWrapper.useBulkCopyOptions(true); - bulkWrapper.setBulkOptions(option); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, false); + testBulkCopyWithTimeout(0); } /** @@ -58,14 +52,18 @@ void testNegativeTimeOut() throws SQLServerException { assertThrows(SQLServerException.class, new org.junit.jupiter.api.function.Executable() { @Override public void execute() throws SQLServerException { - BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); - bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); - SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); - option.setBulkCopyTimeout(-1); - bulkWrapper.useBulkCopyOptions(true); - bulkWrapper.setBulkOptions(option); - BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, false); + testBulkCopyWithTimeout(-1); } }); } + + private void testBulkCopyWithTimeout(int timeout) throws SQLServerException { + BulkCopyTestWrapper bulkWrapper = new BulkCopyTestWrapper(connectionString); + bulkWrapper.setUsingConnection((0 == ThreadLocalRandom.current().nextInt(2)) ? true : false); + SQLServerBulkCopyOptions option = new SQLServerBulkCopyOptions(); + option.setBulkCopyTimeout(timeout); + bulkWrapper.useBulkCopyOptions(true); + bulkWrapper.setBulkOptions(option); + BulkCopyTestUtil.performBulkCopy(bulkWrapper, sourceTable, false); + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java index 1b45d54a5..bbb83e148 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bulkCopy/ISQLServerBulkRecordIssuesTest.java @@ -56,13 +56,11 @@ public class ISQLServerBulkRecordIssuesTest extends AbstractTest { @Test public void testVarchar() throws Exception { variation = "testVarchar"; - BulkDat bData = new BulkDat(variation); - String value = "aa"; + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (smallDATA varchar(2))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); bcOperation.close(); @@ -86,19 +84,20 @@ public void testVarchar() throws Exception { @Test public void testSmalldatetime() throws Exception { variation = "testSmalldatetime"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); String value = ("1954-05-22 02:44:00.0").toString(); query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; stmt.executeUpdate(query); - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); - bcOperation.setDestinationTableName(destTable); - bcOperation.writeToServer(bData); - bcOperation.close(); - - ResultSet rs = stmt.executeQuery("select * from " + destTable); - while (rs.next()) { - assertEquals(rs.getString(1), value); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { + bcOperation.setDestinationTableName(destTable); + bcOperation.writeToServer(bData); + + try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), value); + } + } } } @@ -110,16 +109,14 @@ public void testSmalldatetime() throws Exception { @Test public void testSmalldatetimeOutofRange() throws Exception { variation = "testSmalldatetimeOutofRange"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (smallDATA smalldatetime)"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); fail("BulkCopy executed for testSmalldatetimeOutofRange when it it was expected to fail"); } catch (Exception e) { @@ -141,15 +138,13 @@ public void testSmalldatetimeOutofRange() throws Exception { @Test public void testBinaryColumnAsByte() throws Exception { variation = "testBinaryColumnAsByte"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (col1 binary(5))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); fail("BulkCopy executed for testBinaryColumnAsByte when it it was expected to fail"); } catch (Exception e) { @@ -170,15 +165,13 @@ public void testBinaryColumnAsByte() throws Exception { @Test public void testBinaryColumnAsString() throws Exception { variation = "testBinaryColumnAsString"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (col1 binary(5))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); fail("BulkCopy executed for testBinaryColumnAsString when it it was expected to fail"); } catch (Exception e) { @@ -199,20 +192,18 @@ public void testBinaryColumnAsString() throws Exception { @Test public void testSendValidValueforBinaryColumnAsString() throws Exception { variation = "testSendValidValueforBinaryColumnAsString"; - BulkDat bData = new BulkDat(variation); + BulkData bData = new BulkData(variation); query = "CREATE TABLE " + destTable + " (col1 binary(5))"; stmt.executeUpdate(query); - try { - SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString); + try (SQLServerBulkCopy bcOperation = new SQLServerBulkCopy(connectionString)) { bcOperation.setDestinationTableName(destTable); bcOperation.writeToServer(bData); - bcOperation.close(); - ResultSet rs = stmt.executeQuery("select * from " + destTable); - String value = "0101010000"; - while (rs.next()) { - assertEquals(rs.getString(1), value); + try (ResultSet rs = stmt.executeQuery("select * from " + destTable)) { + while (rs.next()) { + assertEquals(rs.getString(1), "0101010000"); + } } } catch (Exception e) { @@ -258,7 +249,7 @@ public static void afterAllTests() throws SQLException { } -class BulkDat implements ISQLServerBulkRecord { +class BulkData implements ISQLServerBulkRecord { boolean isStringData = false; private class ColumnMetadata { @@ -286,7 +277,7 @@ private class ColumnMetadata { int counter = 0; int rowCount = 1; - BulkDat(String variation) { + BulkData(String variation) { if (variation.equalsIgnoreCase("testVarchar")) { isStringData = true; columnMetadata = new HashMap<>(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java index 8898be8b9..eaad85365 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTest.java @@ -33,10 +33,6 @@ @DisplayName("BVT Test") public class bvtTest extends bvtTestSetup { private static String driverNamePattern = "Microsoft JDBC Driver \\d.\\d for SQL Server"; - private static DBResultSet rs = null; - private static DBPreparedStatement pstmt = null; - private static DBConnection conn = null; - private static DBStatement stmt = null; /** * Connect to specified server and close the connection @@ -46,13 +42,7 @@ public class bvtTest extends bvtTestSetup { @Test @DisplayName("test connection") public void testConnection() throws SQLException { - try { - conn = new DBConnection(connectionString); - conn.close(); - } - finally { - terminateVariation(); - } + try (DBConnection conn = new DBConnection(connectionString)) {} } /** @@ -62,15 +52,11 @@ public void testConnection() throws SQLException { */ @Test public void testConnectionIsClosed() throws SQLException { - try { - conn = new DBConnection(connectionString); + try (DBConnection conn = new DBConnection(connectionString)) { assertTrue(!conn.isClosed(), "BVT connection should not be closed"); conn.close(); assertTrue(conn.isClosed(), "BVT connection should not be open"); } - finally { - terminateVariation(); - } } /** @@ -80,8 +66,7 @@ public void testConnectionIsClosed() throws SQLException { */ @Test public void testDriverNameAndDriverVersion() throws SQLException { - try { - conn = new DBConnection(connectionString); + try (DBConnection conn = new DBConnection(connectionString)) { DatabaseMetaData metaData = conn.getMetaData(); Pattern p = Pattern.compile(driverNamePattern); Matcher m = p.matcher(metaData.getDriverName()); @@ -90,9 +75,6 @@ public void testDriverNameAndDriverVersion() throws SQLException { if (parts.length != 4) assertTrue(true, "Driver version number should be four parts! "); } - finally { - terminateVariation(); - } } /** @@ -103,16 +85,12 @@ public void testDriverNameAndDriverVersion() throws SQLException { @Test public void testCreateStatement() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - String query = "SELECT * FROM " + table1.getEscapedTableName() + ";"; - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName() + ";"; + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { rs.verify(table1); - rs.close(); - } - finally { - terminateVariation(); } } @@ -124,14 +102,10 @@ public void testCreateStatement() throws SQLException { @Test public void testCreateStatementWithQueryTimeout() throws SQLException { - try { - conn = new DBConnection(connectionString + ";querytimeout=10"); - stmt = conn.createStatement(); + try (DBConnection conn = new DBConnection(connectionString + ";querytimeout=10"); + DBStatement stmt = conn.createStatement()) { assertEquals(10, stmt.getQueryTimeout()); } - finally { - terminateVariation(); - } } /** @@ -144,11 +118,11 @@ public void testCreateStatementWithQueryTimeout() throws SQLException { @Test public void testStmtForwardOnlyReadOnly() throws SQLException, ClassNotFoundException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY); - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY); + DBResultSet rs = stmt.executeQuery(query)) { rs.next(); rs.verifyCurrentRow(table1); @@ -164,9 +138,6 @@ public void testStmtForwardOnlyReadOnly() throws SQLException, ClassNotFoundExce } rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -178,11 +149,9 @@ public void testStmtForwardOnlyReadOnly() throws SQLException, ClassNotFoundExce */ @Test public void testStmtScrollInsensitiveReadOnly() throws SQLException, ClassNotFoundException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_INSENSITIVE_CONCUR_READ_ONLY); - - rs = stmt.selectAll(table1); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_INSENSITIVE_CONCUR_READ_ONLY); + DBResultSet rs = stmt.selectAll(table1)) { rs.next(); rs.verifyCurrentRow(table1); rs.afterLast(); @@ -190,9 +159,6 @@ public void testStmtScrollInsensitiveReadOnly() throws SQLException, ClassNotFou rs.verifyCurrentRow(table1); rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -204,12 +170,11 @@ public void testStmtScrollInsensitiveReadOnly() throws SQLException, ClassNotFou @Test public void testStmtScrollSensitiveReadOnly() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_READ_ONLY); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_READ_ONLY); + DBResultSet rs = stmt.executeQuery(query)) { rs.next(); rs.next(); rs.verifyCurrentRow(table1); @@ -219,9 +184,6 @@ public void testStmtScrollSensitiveReadOnly() throws SQLException { rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -232,13 +194,12 @@ public void testStmtScrollSensitiveReadOnly() throws SQLException { */ @Test public void testStmtForwardOnlyUpdateable() throws SQLException { + + String query = "SELECT * FROM " + table1.getEscapedTableName(); - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_UPDATABLE); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_UPDATABLE); + DBResultSet rs = stmt.executeQuery(query)) { rs.next(); // Verify resultset behavior @@ -255,9 +216,6 @@ public void testStmtForwardOnlyUpdateable() throws SQLException { } rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -269,12 +227,11 @@ public void testStmtForwardOnlyUpdateable() throws SQLException { @Test public void testStmtScrollSensitiveUpdatable() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_UPDATABLE); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_SCROLL_SENSITIVE_CONCUR_UPDATABLE); + DBResultSet rs = stmt.executeQuery(query)) { // Verify resultset behavior rs.next(); @@ -285,9 +242,6 @@ public void testStmtScrollSensitiveUpdatable() throws SQLException { rs.absolute(1); rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -298,11 +252,9 @@ public void testStmtScrollSensitiveUpdatable() throws SQLException { @Test public void testStmtSSScrollDynamicOptimisticCC() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(DBResultSetTypes.TYPE_DYNAMIC_CONCUR_OPTIMISTIC); - - rs = stmt.selectAll(table1); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(DBResultSetTypes.TYPE_DYNAMIC_CONCUR_OPTIMISTIC); + DBResultSet rs = stmt.selectAll(table1)) { // Verify resultset behavior rs.next(); @@ -310,9 +262,6 @@ public void testStmtSSScrollDynamicOptimisticCC() throws SQLException { rs.previous(); rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -323,23 +272,16 @@ public void testStmtSSScrollDynamicOptimisticCC() throws SQLException { @Test public void testStmtSserverCursorForwardOnly() throws SQLException { - try { - conn = new DBConnection(connectionString); - DBResultSetTypes rsType = DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY; - stmt = conn.createStatement(rsType.resultsetCursor, rsType.resultSetConcurrency); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - - rs = stmt.executeQuery(query); - + DBResultSetTypes rsType = DBResultSetTypes.TYPE_FORWARD_ONLY_CONCUR_READ_ONLY; + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(rsType.resultsetCursor, rsType.resultSetConcurrency); + DBResultSet rs = stmt.executeQuery(query)) { // Verify resultset behavior rs.next(); rs.verify(table1); } - finally { - terminateVariation(); - } - } /** @@ -350,21 +292,17 @@ public void testStmtSserverCursorForwardOnly() throws SQLException { @Test public void testCreatepreparedStatement() throws SQLException { - try { - conn = new DBConnection(connectionString); - String colName = table1.getColumnName(7); - String value = table1.getRowData(7, 0).toString(); + String colName = table1.getColumnName(7); + String value = table1.getRowData(7, 0).toString(); + String query = "SELECT * from " + table1.getEscapedTableName() + " where [" + colName + "] = ? "; + + try (DBConnection conn = new DBConnection(connectionString); + DBPreparedStatement pstmt = conn.prepareStatement(query)) { - String query = "SELECT * from " + table1.getEscapedTableName() + " where [" + colName + "] = ? "; - - pstmt = conn.prepareStatement(query); pstmt.setObject(1, new BigDecimal(value)); - - rs = pstmt.executeQuery(); + DBResultSet rs = pstmt.executeQuery(); rs.verify(table1); - } - finally { - terminateVariation(); + rs.close(); } } @@ -376,19 +314,14 @@ public void testCreatepreparedStatement() throws SQLException { @Test public void testResultSet() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); - + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { // verify resultSet rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -399,12 +332,11 @@ public void testResultSet() throws SQLException { @Test public void testResultSetAndClose() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { try { if (null != rs) @@ -414,9 +346,6 @@ public void testResultSetAndClose() throws SQLException { fail(e.toString()); } } - finally { - terminateVariation(); - } } /** @@ -426,22 +355,17 @@ public void testResultSetAndClose() throws SQLException { */ @Test public void testTwoResultsetsDifferentStmt() throws SQLException { + + String query = "SELECT * FROM " + table1.getEscapedTableName(); + String query2 = "SELECT * FROM " + table2.getEscapedTableName(); - DBStatement stmt1 = null; - DBStatement stmt2 = null; - DBResultSet rs1 = null; - DBResultSet rs2 = null; - try { - conn = new DBConnection(connectionString); - stmt1 = conn.createStatement(); - stmt2 = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs1 = stmt1.executeQuery(query); - - String query2 = "SELECT * FROM " + table2.getEscapedTableName(); - rs2 = stmt2.executeQuery(query2); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt1 = conn.createStatement(); + DBStatement stmt2 = conn.createStatement()) { + DBResultSet rs1 = stmt1.executeQuery(query); + DBResultSet rs2 = stmt2.executeQuery(query2); + // Interleave resultset calls rs1.next(); rs1.verifyCurrentRow(table1); @@ -453,21 +377,7 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { rs1.close(); rs2.next(); rs2.verify(table2); - } - finally { - if (null != rs1) { - rs1.close(); - } - if (null != rs2) { - rs2.close(); - } - if (null != stmt1) { - stmt1.close(); - } - if (null != stmt2) { - stmt2.close(); - } - terminateVariation(); + rs2.close(); } } @@ -479,18 +389,14 @@ public void testTwoResultsetsDifferentStmt() throws SQLException { @Test public void testTwoResultsetsSameStmt() throws SQLException { - DBResultSet rs1 = null; - DBResultSet rs2 = null; - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs1 = stmt.executeQuery(query); - - String query2 = "SELECT * FROM " + table2.getEscapedTableName(); - rs2 = stmt.executeQuery(query2); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + String query2 = "SELECT * FROM " + table2.getEscapedTableName(); + + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement()) { + DBResultSet rs1 = stmt.executeQuery(query); + DBResultSet rs2 = stmt.executeQuery(query2); // Interleave resultset calls. rs is expected to be closed try { rs1.next(); @@ -509,15 +415,7 @@ public void testTwoResultsetsSameStmt() throws SQLException { rs1.close(); rs2.next(); rs2.verify(table2); - } - finally { - if (null != rs1) { - rs1.close(); - } - if (null != rs2) { - rs2.close(); - } - terminateVariation(); + rs2.close(); } } @@ -528,12 +426,10 @@ public void testTwoResultsetsSameStmt() throws SQLException { */ @Test public void testResultSetAndCloseStmt() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); + String query = "SELECT * FROM " + table1.getEscapedTableName(); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { stmt.close(); // this should close the resultSet try { @@ -542,10 +438,7 @@ public void testResultSetAndCloseStmt() throws SQLException { catch (SQLException e) { assertEquals(e.toString(), "com.microsoft.sqlserver.jdbc.SQLServerException: The result set is closed."); } - assertTrue(true, "Previouse one should have thrown exception!"); - } - finally { - terminateVariation(); + assertTrue(true, "Previous one should have thrown exception!"); } } @@ -557,18 +450,12 @@ public void testResultSetAndCloseStmt() throws SQLException { @Test public void testResultSetSelectMethod() throws SQLException { - try { - conn = new DBConnection(connectionString + ";selectMethod=cursor;"); - stmt = conn.createStatement(); - - String query = "SELECT * FROM " + table1.getEscapedTableName(); - rs = stmt.executeQuery(query); - + String query = "SELECT * FROM " + table1.getEscapedTableName(); + try (DBConnection conn = new DBConnection(connectionString + ";selectMethod=cursor;"); + DBStatement stmt = conn.createStatement(); + DBResultSet rs = stmt.executeQuery(query)) { rs.verify(table1); } - finally { - terminateVariation(); - } } /** @@ -579,34 +466,10 @@ public void testResultSetSelectMethod() throws SQLException { @AfterAll public static void terminate() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement()) { stmt.execute("if object_id('" + table1.getEscapedTableName() + "','U') is not null" + " drop table " + table1.getEscapedTableName()); stmt.execute("if object_id('" + table2.getEscapedTableName() + "','U') is not null" + " drop table " + table2.getEscapedTableName()); } - finally { - terminateVariation(); - } - } - - /** - * cleanup after tests - * - * @throws SQLException - */ - public static void terminateVariation() throws SQLException { - if (conn != null && !conn.isClosed()) { - try { - conn.close(); - } - finally { - if (null != rs) - rs.close(); - if (null != stmt) - stmt.close(); - } - } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java index 684bfd81d..0306d6f1d 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/bvt/bvtTestSetup.java @@ -24,18 +24,14 @@ */ @RunWith(JUnitPlatform.class) public class bvtTestSetup extends AbstractTest { - private static DBConnection conn = null; - private static DBStatement stmt = null; static DBTable table1; static DBTable table2; @BeforeAll public static void init() throws SQLException { - try { - conn = new DBConnection(connectionString); - stmt = conn.createStatement(); - + try (DBConnection conn = new DBConnection(connectionString); + DBStatement stmt = conn.createStatement()) { // create tables table1 = new DBTable(true); stmt.createTable(table1); @@ -44,14 +40,5 @@ public static void init() throws SQLException { stmt.createTable(table2); stmt.populateTable(table2); } - finally { - if (null != stmt) { - stmt.close(); - } - if (null != conn && !conn.isClosed()) { - conn.close(); - } - } } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java index d0271714d..dad9c195f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/callablestatement/CallableStatementTest.java @@ -1,9 +1,12 @@ package com.microsoft.sqlserver.jdbc.callablestatement; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; @@ -17,6 +20,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; +import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.Utils; @@ -28,6 +32,7 @@ public class CallableStatementTest extends AbstractTest { private static String tableNameGUID = "uniqueidentifier_Table"; private static String outputProcedureNameGUID = "uniqueidentifier_SP"; private static String setNullProcedureName = "CallableStatementTest_setNull_SP"; + private static String inputParamsProcedureName = "CallableStatementTest_inputParams_SP"; private static Connection connection = null; private static Statement stmt = null; @@ -45,10 +50,12 @@ public static void setupTest() throws SQLException { Utils.dropTableIfExists(tableNameGUID, stmt); Utils.dropProcedureIfExists(outputProcedureNameGUID, stmt); Utils.dropProcedureIfExists(setNullProcedureName, stmt); + Utils.dropProcedureIfExists(inputParamsProcedureName, stmt); - createGUIDTable(); - createGUIDStoredProcedure(); - createSetNullPreocedure(); + createGUIDTable(stmt); + createGUIDStoredProcedure(stmt); + createSetNullPreocedure(stmt); + createInputParamsProcedure(stmt); } /** @@ -59,17 +66,14 @@ public static void setupTest() throws SQLException { @Test public void getStringGUIDTest() throws SQLException { - SQLServerCallableStatement callableStatement = null; - try { - String sql = "{call " + outputProcedureNameGUID + "(?)}"; - - callableStatement = (SQLServerCallableStatement) connection.prepareCall(sql); + String sql = "{call " + outputProcedureNameGUID + "(?)}"; + + try (SQLServerCallableStatement callableStatement = (SQLServerCallableStatement) connection.prepareCall(sql)) { UUID originalValue = UUID.randomUUID(); callableStatement.registerOutParameter(1, microsoft.sql.Types.GUID); callableStatement.setObject(1, originalValue.toString(), microsoft.sql.Types.GUID); - callableStatement.execute(); String retrievedValue = callableStatement.getString(1); @@ -77,11 +81,6 @@ public void getStringGUIDTest() throws SQLException { assertEquals(originalValue.toString().toLowerCase(), retrievedValue.toLowerCase()); } - finally { - if (null != callableStatement) { - callableStatement.close(); - } - } } /** @@ -93,17 +92,14 @@ public void getStringGUIDTest() throws SQLException { public void getSetNullWithTypeVarchar() throws SQLException { String polishchar = "\u0143"; - SQLServerCallableStatement cs = null; - SQLServerCallableStatement cs2 = null; - try { - SQLServerDataSource ds = new SQLServerDataSource(); - ds.setURL(connectionString); - ds.setSendStringParametersAsUnicode(true); - connection = ds.getConnection(); - - String sql = "{? = call " + setNullProcedureName + " (?,?)}"; + SQLServerDataSource ds = new SQLServerDataSource(); + ds.setURL(connectionString); + ds.setSendStringParametersAsUnicode(true); + String sql = "{? = call " + setNullProcedureName + " (?,?)}"; + try (Connection connection = ds.getConnection(); + SQLServerCallableStatement cs = (SQLServerCallableStatement) connection.prepareCall(sql); + SQLServerCallableStatement cs2 = (SQLServerCallableStatement) connection.prepareCall(sql)){ - cs = (SQLServerCallableStatement) connection.prepareCall(sql); cs.registerOutParameter(1, Types.INTEGER); cs.setString(2, polishchar); cs.setString(3, null); @@ -112,7 +108,6 @@ public void getSetNullWithTypeVarchar() throws SQLException { String expected = cs.getString(3); - cs2 = (SQLServerCallableStatement) connection.prepareCall(sql); cs2.registerOutParameter(1, Types.INTEGER); cs2.setString(2, polishchar); cs2.setNull(3, Types.VARCHAR); @@ -120,19 +115,51 @@ public void getSetNullWithTypeVarchar() throws SQLException { cs2.execute(); String actual = cs2.getString(3); - + assertEquals(expected, actual); } - finally { - if (null != cs) { - cs.close(); - } - if (null != cs2) { - cs2.close(); + } + + + /** + * recognize parameter names with and without leading '@' + * + * @throws SQLException + */ + @Test + public void inputParamsTest() throws SQLException { + String call = "{CALL " + inputParamsProcedureName + " (?,?)}"; + ResultSet rs = null; + + // the historical way: no leading '@', parameter names respected (not positional) + CallableStatement cs1 = connection.prepareCall(call); + cs1.setString("p2", "bar"); + cs1.setString("p1", "foo"); + rs = cs1.executeQuery(); + rs.next(); + assertEquals("foobar", rs.getString(1)); + + // the "new" way: leading '@', parameter names still respected (not positional) + CallableStatement cs2 = connection.prepareCall(call); + cs2.setString("@p2", "world!"); + cs2.setString("@p1", "Hello "); + rs = cs2.executeQuery(); + rs.next(); + assertEquals("Hello world!", rs.getString(1)); + + // sanity check: unrecognized parameter name + CallableStatement cs3 = connection.prepareCall(call); + try { + cs3.setString("@whatever", "junk"); + fail("SQLServerException should have been thrown"); + } catch (SQLServerException sse) { + if (!sse.getMessage().startsWith("Parameter @whatever was not defined")) { + fail("Unexpected content in exception message"); } } - } + } + /** * Cleanup after test * @@ -143,6 +170,7 @@ public static void cleanup() throws SQLException { Utils.dropTableIfExists(tableNameGUID, stmt); Utils.dropProcedureIfExists(outputProcedureNameGUID, stmt); Utils.dropProcedureIfExists(setNullProcedureName, stmt); + Utils.dropProcedureIfExists(inputParamsProcedureName, stmt); if (null != stmt) { stmt.close(); @@ -152,17 +180,30 @@ public static void cleanup() throws SQLException { } } - private static void createGUIDStoredProcedure() throws SQLException { + private static void createGUIDStoredProcedure(Statement stmt) throws SQLException { String sql = "CREATE PROCEDURE " + outputProcedureNameGUID + "(@p1 uniqueidentifier OUTPUT) AS SELECT @p1 = c1 FROM " + tableNameGUID + ";"; stmt.execute(sql); } - private static void createGUIDTable() throws SQLException { + private static void createGUIDTable(Statement stmt) throws SQLException { String sql = "CREATE TABLE " + tableNameGUID + " (c1 uniqueidentifier null)"; stmt.execute(sql); } - private static void createSetNullPreocedure() throws SQLException { + private static void createSetNullPreocedure(Statement stmt) throws SQLException { stmt.execute("create procedure " + setNullProcedureName + " (@p1 nvarchar(255), @p2 nvarchar(255) output) as select @p2=@p1 return 0"); } + + private static void createInputParamsProcedure(Statement stmt) throws SQLException { + String sql = + "CREATE PROCEDURE [dbo].[CallableStatementTest_inputParams_SP] " + + " @p1 nvarchar(max) = N'parameter1', " + + " @p2 nvarchar(max) = N'parameter2' " + + "AS " + + "BEGIN " + + " SET NOCOUNT ON; " + + " SELECT @p1 + @p2 AS result; " + + "END "; + stmt.execute(sql); + } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java index c8a415540..2acf5f002 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/ConnectionDriverTest.java @@ -123,8 +123,7 @@ public void testEncryptedConnection() throws SQLException { ds.setEncrypt(true); ds.setTrustServerCertificate(true); ds.setPacketSize(8192); - Connection con = ds.getConnection(); - con.close(); + try(Connection con = ds.getConnection()) {} } @Test @@ -172,25 +171,25 @@ public void testConnectionEvents() throws SQLException { // Attach the Event listener and listen for connection events. MyEventListener myE = new MyEventListener(); - pooledConnection.addConnectionEventListener(myE); // ConnectionListener - // implements - // ConnectionEventListener - Connection con = pooledConnection.getConnection(); - Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); - - boolean exceptionThrown = false; - try { - // raise a severe exception and make sure that the connection is not - // closed. - stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG"); + pooledConnection.addConnectionEventListener(myE); // ConnectionListener implements ConnectionEventListener + + try(Connection con = pooledConnection.getConnection(); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) { + + boolean exceptionThrown = false; + try { + // raise a severe exception and make sure that the connection is not + // closed. + stmt.executeUpdate("RAISERROR ('foo', 20,1) WITH LOG"); + } + catch (Exception e) { + exceptionThrown = true; + } + assertTrue(exceptionThrown, "Expected exception is not thrown."); + + // Check to see if error occurred. + assertTrue(myE.errorOccurred, "Error occurred is not called."); } - catch (Exception e) { - exceptionThrown = true; - } - assertTrue(exceptionThrown, "Expected exception is not thrown."); - - // Check to see if error occurred. - assertTrue(myE.errorOccurred, "Error occurred is not called."); // make sure that connection is closed. } @@ -204,23 +203,18 @@ public void testConnectionPoolGetTwice() throws SQLException { // Attach the Event listener and listen for connection events. MyEventListener myE = new MyEventListener(); - pooledConnection.addConnectionEventListener(myE); // ConnectionListener - // implements - // ConnectionEventListener - - Connection con = pooledConnection.getConnection(); - Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + pooledConnection.addConnectionEventListener(myE); // ConnectionListener implements ConnectionEventListener - // raise a non severe exception and make sure that the connection is not - // closed. + Connection con = pooledConnection.getConnection(); + Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + // raise a non severe exception and make sure that the connection is not closed. stmt.executeUpdate("RAISERROR ('foo', 3,1) WITH LOG"); - // not a serious error there should not be any errors. assertTrue(!myE.errorOccurred, "Error occurred is called."); // check to make sure that connection is not closed. - assertTrue(!con.isClosed(), "Connection is closed."); - - con.close(); + assertTrue(!con.isClosed(), "Connection is closed."); + stmt.close(); + con.close(); // check to make sure that connection is closed. assertTrue(con.isClosed(), "Connection is not closed."); } @@ -242,36 +236,34 @@ public void testConnectionClosed() throws SQLException { exceptionThrown = true; } assertTrue(exceptionThrown, "Expected exception is not thrown."); - + // check to make sure that connection is closed. assertTrue(con.isClosed(), "Connection is not closed."); } @Test public void testIsWrapperFor() throws SQLException, ClassNotFoundException { - Connection conn = DriverManager.getConnection(connectionString); - SQLServerConnection ssconn = (SQLServerConnection) conn; - boolean isWrapper; - isWrapper = ssconn.isWrapperFor(ssconn.getClass()); - assertTrue(isWrapper, "SQLServerConnection supports unwrapping"); - assertEquals(ssconn.TRANSACTION_SNAPSHOT, ssconn.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); - - isWrapper = ssconn.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); - assertTrue(isWrapper, "ISQLServerConnection supports unwrapping"); - ISQLServerConnection iSql = (ISQLServerConnection) ssconn.unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); - assertEquals(iSql.TRANSACTION_SNAPSHOT, iSql.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); - - ssconn.unwrap(Class.forName("java.sql.Connection")); - - conn.close(); + try(Connection conn = DriverManager.getConnection(connectionString); + SQLServerConnection ssconn = (SQLServerConnection) conn) { + boolean isWrapper; + isWrapper = ssconn.isWrapperFor(ssconn.getClass()); + assertTrue(isWrapper, "SQLServerConnection supports unwrapping"); + assertEquals(ssconn.TRANSACTION_SNAPSHOT, ssconn.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); + + isWrapper = ssconn.isWrapperFor(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); + assertTrue(isWrapper, "ISQLServerConnection supports unwrapping"); + ISQLServerConnection iSql = (ISQLServerConnection) ssconn.unwrap(Class.forName("com.microsoft.sqlserver.jdbc.ISQLServerConnection")); + assertEquals(iSql.TRANSACTION_SNAPSHOT, iSql.TRANSACTION_SNAPSHOT, "Cant access the TRANSACTION_SNAPSHOT "); + + ssconn.unwrap(Class.forName("java.sql.Connection")); + } } @Test public void testNewConnection() throws SQLException { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - assertTrue(conn.isValid(0), "Newly created connection should be valid"); - - conn.close(); + try(SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + assertTrue(conn.isValid(0), "Newly created connection should be valid"); + } } @Test @@ -283,46 +275,46 @@ public void testClosedConnection() throws SQLException { @Test public void testNegativeTimeout() throws Exception { - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString); - try { - conn.isValid(-42); - throw new Exception("No exception thrown with negative timeout"); - } - catch (SQLException e) { - assertEquals(e.getMessage(), "The query timeout value -42 is not valid.", "Wrong exception message"); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString)) { + try { + conn.isValid(-42); + throw new Exception("No exception thrown with negative timeout"); + } + catch (SQLException e) { + assertEquals(e.getMessage(), "The query timeout value -42 is not valid.", "Wrong exception message"); + } } - - conn.close(); } @Test public void testDeadConnection() throws SQLException { assumeTrue(!DBConnection.isSqlAzure(DriverManager.getConnection(connectionString)), "Skipping test case on Azure SQL."); - SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";responseBuffering=adaptive"); - Statement stmt = null; - - String tableName = RandomUtil.getIdentifier("Table"); - tableName = DBTable.escapeIdentifier(tableName); - - conn.setAutoCommit(false); - stmt = conn.createStatement(); - stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key)"); - for (int i = 0; i < 80; i++) { - stmt.executeUpdate("INSERT INTO " + tableName + "(col1) values (" + i + ")"); - } - conn.commit(); - try { - stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + tableName + " as x1, " + tableName - + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); - } - catch (SQLServerException e) { - assertEquals(e.getMessage(), "Connection reset", "Unknown Exception"); - } - finally { - DriverManager.getConnection(connectionString).createStatement().execute("drop table " + tableName); + try (SQLServerConnection conn = (SQLServerConnection) DriverManager.getConnection(connectionString + ";responseBuffering=adaptive")) { + + Statement stmt = null; + String tableName = RandomUtil.getIdentifier("Table"); + tableName = DBTable.escapeIdentifier(tableName); + + conn.setAutoCommit(false); + stmt = conn.createStatement(); + stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 int primary key)"); + for (int i = 0; i < 80; i++) { + stmt.executeUpdate("INSERT INTO " + tableName + "(col1) values (" + i + ")"); + } + conn.commit(); + try { + stmt.execute("SELECT x1.col1 as foo, x2.col1 as bar, x1.col1 as eeep FROM " + tableName + " as x1, " + tableName + + " as x2; RAISERROR ('Oops', 21, 42) WITH LOG"); + } + catch (SQLServerException e) { + assertEquals(e.getMessage(), "Connection reset", "Unknown Exception"); + } + finally { + DriverManager.getConnection(connectionString).createStatement().execute("drop table " + tableName); + } + assertEquals(conn.isValid(5), false, "Dead connection should be invalid"); } - assertEquals(conn.isValid(5), false, "Dead connection should be invalid"); } @Test diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java index 9645d5b95..f71da3f7f 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/DBMetadataTest.java @@ -11,13 +11,13 @@ import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import com.microsoft.sqlserver.jdbc.SQLServerDataSource; -import com.microsoft.sqlserver.jdbc.SQLServerException; import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBTable; import com.microsoft.sqlserver.testframework.util.RandomUtil; @@ -32,26 +32,27 @@ public void testDatabaseMetaData() throws SQLException { SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); - Connection con = ds.getConnection(); - - // drop function String sqlDropFunction = "if exists (select * from dbo.sysobjects where id = object_id(N'[dbo]." + functionName + "')" + "and xtype in (N'FN', N'IF', N'TF'))" + "drop function " + functionName; - con.createStatement().execute(sqlDropFunction); - - // create function String sqlCreateFunction = "CREATE FUNCTION " + functionName + " (@text varchar(8000), @delimiter varchar(20) = ' ') RETURNS @Strings TABLE " + "(position int IDENTITY PRIMARY KEY, value varchar(8000)) AS BEGIN INSERT INTO @Strings VALUES ('DDD') RETURN END "; - con.createStatement().execute(sqlCreateFunction); - - DatabaseMetaData md = con.getMetaData(); - ResultSet arguments = md.getProcedureColumns(null, null, null, "@TABLE_RETURN_VALUE"); - - if (arguments.next()) { - arguments.getString("COLUMN_NAME"); - arguments.getString("DATA_TYPE"); // call this function to make sure it does not crash + + try (Connection con = ds.getConnection(); + Statement stmt = con.createStatement()) { + // drop function + stmt.execute(sqlDropFunction); + // create function + stmt.execute(sqlCreateFunction); + + DatabaseMetaData md = con.getMetaData(); + try (ResultSet arguments = md.getProcedureColumns(null, null, null, "@TABLE_RETURN_VALUE")) { + + if (arguments.next()) { + arguments.getString("COLUMN_NAME"); + arguments.getString("DATA_TYPE"); // call this function to make sure it does not crash + } + } + stmt.execute(sqlDropFunction); } - - con.createStatement().execute(sqlDropFunction); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java index 08ba2a58a..57803a32e 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/NativeMSSQLDataSourceTest.java @@ -43,36 +43,34 @@ public void testNativeMSSQLDataSource() throws SQLException { @Test public void testSerialization() throws IOException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - ObjectOutput objectOutput = new ObjectOutputStream(outputStream); - - SQLServerDataSource ds = new SQLServerDataSource(); - ds.setLogWriter(new PrintWriter(new ByteArrayOutputStream())); - - objectOutput.writeObject(ds); - objectOutput.flush(); + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ObjectOutput objectOutput = new ObjectOutputStream(outputStream)) { + SQLServerDataSource ds = new SQLServerDataSource(); + ds.setLogWriter(new PrintWriter(new ByteArrayOutputStream())); + + objectOutput.writeObject(ds); + objectOutput.flush(); + } } @Test - public void testDSNormal() throws SQLServerException, ClassNotFoundException, IOException { + public void testDSNormal() throws ClassNotFoundException, IOException, SQLException { SQLServerDataSource ds = new SQLServerDataSource(); ds.setURL(connectionString); - Connection conn = ds.getConnection(); + try (Connection conn = ds.getConnection()) {} ds = testSerial(ds); - conn = ds.getConnection(); + try (Connection conn = ds.getConnection()) {} } @Test - public void testDSTSPassword() throws SQLServerException, ClassNotFoundException, IOException { + public void testDSTSPassword() throws ClassNotFoundException, IOException, SQLException { SQLServerDataSource ds = new SQLServerDataSource(); System.setProperty("java.net.preferIPv6Addresses", "true"); ds.setURL(connectionString); ds.setTrustStorePassword("wrong_password"); - Connection conn = ds.getConnection(); + try (Connection conn = ds.getConnection()) {} ds = testSerial(ds); - try { - conn = ds.getConnection(); - } + try (Connection conn = ds.getConnection()) {} catch (SQLServerException e) { assertEquals("The DataSource trustStore password needs to be set.", e.getMessage()); } @@ -106,13 +104,16 @@ public void testInterfaceWrapping() throws ClassNotFoundException, SQLException } private SQLServerDataSource testSerial(SQLServerDataSource ds) throws IOException, ClassNotFoundException { - java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream(); - java.io.ObjectOutput objectOutput = new java.io.ObjectOutputStream(outputStream); - objectOutput.writeObject(ds); - objectOutput.flush(); - ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray())); - SQLServerDataSource dtn; - dtn = (SQLServerDataSource) in.readObject(); - return dtn; + try (java.io.ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream(); + java.io.ObjectOutput objectOutput = new java.io.ObjectOutputStream(outputStream)) { + objectOutput.writeObject(ds); + objectOutput.flush(); + + try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(outputStream.toByteArray()))) { + SQLServerDataSource dtn; + dtn = (SQLServerDataSource) in.readObject(); + return dtn; + } + } } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java index 1c254b54b..1a51deb34 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/connection/PoolingTest.java @@ -59,17 +59,15 @@ public void testPooling() throws SQLException { XADataSource1.setDatabaseName("tempdb"); PooledConnection pc = XADataSource1.getPooledConnection(); - Connection conn = pc.getConnection(); - - // create table in tempdb database - conn.createStatement().execute("create table [" + tempTableName + "] (myid int)"); - conn.createStatement().execute("insert into [" + tempTableName + "] values (1)"); - conn.close(); - - conn = pc.getConnection(); + try (Connection conn = pc.getConnection()) { + + // create table in tempdb database + conn.createStatement().execute("create table [" + tempTableName + "] (myid int)"); + conn.createStatement().execute("insert into [" + tempTableName + "] values (1)"); + } boolean tempTableFileRemoved = false; - try { + try (Connection conn = pc.getConnection()) { conn.createStatement().executeQuery("select * from [" + tempTableName + "]"); } catch (SQLServerException e) { @@ -109,12 +107,12 @@ public void testConnectionPoolConnFunctions() throws SQLException { ds.setURL(connectionString); PooledConnection pc = ds.getPooledConnection(); - Connection con = pc.getConnection(); - - Statement statement = con.createStatement(); - statement.execute(sql1); - statement.execute(sql2); - con.clearWarnings(); + try (Connection con = pc.getConnection(); + Statement statement = con.createStatement()) { + statement.execute(sql1); + statement.execute(sql2); + con.clearWarnings(); + } pc.close(); } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java index da20156c7..2e1fe11f6 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/datatypes/TVPWithSqlVariantTest.java @@ -378,6 +378,23 @@ public void testIntStoredProcedure() throws SQLServerException { Cstatement.close(); } } + + /** + * Test for allowing duplicate columns + * + * @throws SQLServerException + */ + @Test + public void testDuplicateColumn() throws SQLServerException { + tvp = new SQLServerDataTable(); + tvp.addColumnMetadata("c1", microsoft.sql.Types.SQL_VARIANT); + tvp.addColumnMetadata("c2", microsoft.sql.Types.SQL_VARIANT); + try { + tvp.addColumnMetadata("c2", microsoft.sql.Types.SQL_VARIANT); + } catch (SQLServerException e) { + assertEquals(e.getMessage(), "A column name c2 already belongs to this SQLServerDataTable."); + } + } private static String[] createNumericValues() { Boolean C1_BIT; diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java index 95f2962c2..e93f1c150 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/CallableMixedTest.java @@ -22,6 +22,7 @@ import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -31,7 +32,6 @@ @RunWith(JUnitPlatform.class) public class CallableMixedTest extends AbstractTest { Connection connection = null; - Statement statement = null; String tableN = RandomUtil.getIdentifier("TFOO3"); String procN = RandomUtil.getIdentifier("SPFOO3"); String tableName = AbstractSQLGenerator.escapeIdentifier(tableN); @@ -39,71 +39,62 @@ public class CallableMixedTest extends AbstractTest { /** * Tests Callable mix + * * @throws SQLException */ @Test @DisplayName("Test CallableMix") public void datatypesTest() throws SQLException { - connection = DriverManager.getConnection(connectionString); - statement = connection.createStatement(); + try (Connection connection = DriverManager.getConnection(connectionString); Statement statement = connection.createStatement();) { - try { - statement.executeUpdate("DROP TABLE " + tableName); - statement.executeUpdate(" DROP PROCEDURE " + procName); - } - catch (Exception e) { - } + statement.executeUpdate("create table " + tableName + " (c1_int int primary key, col2 int)"); + statement.executeUpdate("Insert into " + tableName + " values(0, 1)"); - statement.executeUpdate("create table " + tableName + " (c1_int int primary key, col2 int)"); - statement.executeUpdate("Insert into " + tableName + " values(0, 1)"); - statement.close(); - Statement stmt = connection.createStatement(); - stmt.executeUpdate("CREATE PROCEDURE " + procName - + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " - + tableName + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); - stmt.close(); + statement.executeUpdate("CREATE PROCEDURE " + procName + + " (@p2_int int, @p2_int_out int OUTPUT, @p4_smallint smallint, @p4_smallint_out smallint OUTPUT) AS begin transaction SELECT * FROM " + + tableName + " ; SELECT @p2_int_out=@p2_int, @p4_smallint_out=@p4_smallint commit transaction RETURN -2147483648"); - CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + procName + " (?, ?, ?, ?) }"); - callableStatement.registerOutParameter((int) 1, (int) 4); - callableStatement.setObject((int) 2, Integer.valueOf("31"), (int) 4); - callableStatement.registerOutParameter((int) 3, (int) 4); - callableStatement.registerOutParameter((int) 5, java.sql.Types.BINARY); - callableStatement.registerOutParameter((int) 5, (int) 5); - callableStatement.setObject((int) 4, Short.valueOf("-5372"), (int) 5); + try (CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + procName + " (?, ?, ?, ?) }")) { + callableStatement.registerOutParameter((int) 1, (int) 4); + callableStatement.setObject((int) 2, Integer.valueOf("31"), (int) 4); + callableStatement.registerOutParameter((int) 3, (int) 4); + callableStatement.registerOutParameter((int) 5, java.sql.Types.BINARY); + callableStatement.registerOutParameter((int) 5, (int) 5); + callableStatement.setObject((int) 4, Short.valueOf("-5372"), (int) 5); - // get results and a value - ResultSet rs = callableStatement.executeQuery(); - rs.next(); + // get results and a value + ResultSet rs = callableStatement.executeQuery(); + rs.next(); - assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); - assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); + assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); + assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); - // do nothing and reexecute - rs = callableStatement.executeQuery(); - // get the param without getting the resultset - rs = callableStatement.executeQuery(); - assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); + // do nothing and reexecute + rs = callableStatement.executeQuery(); + // get the param without getting the resultset + rs = callableStatement.executeQuery(); + assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); - rs = callableStatement.executeQuery(); - rs.next(); + rs = callableStatement.executeQuery(); + rs.next(); - assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); - assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); - assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); - rs = callableStatement.executeQuery(); - callableStatement.close(); - rs.close(); - stmt.close(); - terminateVariation(); + assertEquals(rs.getInt(1), 0, "Received data not equal to setdata"); + assertEquals(callableStatement.getInt((int) 1), -2147483648, "Received data not equal to setdata"); + assertEquals(callableStatement.getInt((int) 5), -5372, "Received data not equal to setdata"); + rs = callableStatement.executeQuery(); + rs.close(); + } + terminateVariation(statement); + } } - - private void terminateVariation() throws SQLException { - statement = connection.createStatement(); - statement.executeUpdate("DROP TABLE " + tableName); - statement.executeUpdate(" DROP PROCEDURE " + procName); - statement.close(); - connection.close(); + /** + * Cleanups + * + * @throws SQLException + */ + private void terminateVariation(Statement statement) throws SQLException { + Utils.dropTableIfExists(tableName, statement); + Utils.dropProcedureIfExists(procName, statement); } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java index cc9e0e69f..6e3563101 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/LimitEscapeTest.java @@ -32,6 +32,7 @@ import org.junit.runner.RunWith; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; /** * Testing with LimitEscape queries @@ -782,13 +783,10 @@ public static void afterAll() throws Exception { Statement stmt = conn.createStatement(); try { - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t1', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t1"); - - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t2', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t2"); - - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t3', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t3"); - - stmt.executeUpdate("IF OBJECT_ID (N'UnitStatement_LimitEscape_t4', N'U') IS NOT NULL DROP TABLE UnitStatement_LimitEscape_t4"); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t1", stmt); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t2", stmt); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t3", stmt); + Utils.dropTableIfExists("UnitStatement_LimitEscape_t4", stmt); } catch (Exception ex) { fail(ex.toString()); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java index 43b0bccc1..54ebcdde2 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/MergeTest.java @@ -10,7 +10,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; +import java.sql.Connection; +import java.sql.DriverManager; import java.sql.ResultSet; +import java.sql.Statement; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.DisplayName; @@ -21,6 +24,7 @@ import com.microsoft.sqlserver.testframework.AbstractTest; import com.microsoft.sqlserver.testframework.DBConnection; import com.microsoft.sqlserver.testframework.DBStatement; +import com.microsoft.sqlserver.testframework.Utils; /** * Testing merge queries @@ -44,52 +48,42 @@ public class MergeTest extends AbstractTest { + "VALUES (SOURCE.CricketTeamID, SOURCE.CricketTeamCountry, SOURCE.CricketTeamContinent) " + "WHEN NOT MATCHED BY SOURCE THEN DELETE;"; - /** * Merge test + * * @throws Exception */ @Test @DisplayName("Merge Test") public void runTest() throws Exception { - DBConnection conn = new DBConnection(connectionString); - if (conn.getServerVersion() >= 10) { - DBStatement stmt = conn.createStatement(); - stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - stmt.executeUpdate(setupTables); - stmt.executeUpdate(mergeCmd2); - int updateCount = stmt.getUpdateCount(); - assertEquals(updateCount, 3, "Received the wrong update count!"); - - if (null != stmt) { - stmt.close(); - } - if (null != conn) { - conn.close(); + try (DBConnection conn = new DBConnection(connectionString)) { + if (conn.getServerVersion() >= 10) { + try (DBStatement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);) { + stmt.executeUpdate(setupTables); + stmt.executeUpdate(mergeCmd2); + int updateCount = stmt.getUpdateCount(); + assertEquals(updateCount, 3, "Received the wrong update count!"); + + } } } } - + /** * Clean up + * * @throws Exception */ @AfterAll public static void afterAll() throws Exception { - DBConnection conn = new DBConnection(connectionString); - DBStatement stmt = conn.createStatement(); - try { - stmt.executeUpdate("IF OBJECT_ID (N'dbo.CricketTeams', N'U') IS NOT NULL DROP TABLE dbo.CricketTeams"); - } - catch (Exception ex) { - fail(ex.toString()); - } - finally { - stmt.close(); - conn.close(); + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists("dbo.CricketTeams", stmt); + } + catch (Exception ex) { + fail(ex.toString()); + } } - } - } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java index be8139e39..2ee818313 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/NamedParamMultiPartTest.java @@ -32,87 +32,99 @@ */ @RunWith(JUnitPlatform.class) public class NamedParamMultiPartTest extends AbstractTest { - private static final String dataPut = "eminem "; + private static final String dataPut = "eminem"; private static Connection connection = null; - private static CallableStatement cs = null; + String procedureName = "mystoredproc"; /** * setup + * * @throws SQLException */ @BeforeAll public static void beforeAll() throws SQLException { connection = DriverManager.getConnection(connectionString); - Statement statement = connection.createStatement(); - Utils.dropProcedureIfExists("mystoredproc", statement); - statement.executeUpdate("CREATE PROCEDURE [mystoredproc] (@p_out varchar(255) OUTPUT) AS set @p_out = '" + dataPut + "'"); - statement.close(); - } + try (Statement statement = connection.createStatement()) { + Utils.dropProcedureIfExists("mystoredproc", statement); + statement.executeUpdate("CREATE PROCEDURE [mystoredproc] (@p_out varchar(255) OUTPUT) AS set @p_out = '" + dataPut + "'"); + } + } + /** * Stored procedure call + * * @throws Exception */ @Test public void update1() throws Exception { - cs = connection.prepareCall("{ CALL [mystoredproc] (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - String data = cs.getString("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + String data = cs.getString("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update2() throws Exception { - cs = connection.prepareCall("{ CALL [dbo].[mystoredproc] (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update3() throws Exception { String catalog = connection.getCatalog(); String storedproc = "[" + catalog + "]" + ".[dbo].[mystoredproc]"; - cs = connection.prepareCall("{ CALL " + storedproc + " (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update4() throws Exception { - cs = connection.prepareCall("{ CALL mystoredproc (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Stored procedure call + * * @throws Exception */ @Test public void update5() throws Exception { - cs = connection.prepareCall("{ CALL dbo.mystoredproc (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + try (CallableStatement cs = connection.prepareCall("{ CALL " + procedureName + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** @@ -122,29 +134,29 @@ public void update5() throws Exception { @Test public void update6() throws Exception { String catalog = connection.getCatalog(); - String storedproc = catalog + ".dbo.mystoredproc"; - cs = connection.prepareCall("{ CALL " + storedproc + " (?) }"); - cs.registerOutParameter("p_out", Types.VARCHAR); - cs.executeUpdate(); - Object data = cs.getObject("p_out"); - assertEquals(data, dataPut, "Received data not equal to setdata"); + String storedproc = catalog + ".dbo." + procedureName; + try (CallableStatement cs = connection.prepareCall("{ CALL " + storedproc + " (?) }")) { + cs.registerOutParameter("p_out", Types.VARCHAR); + cs.executeUpdate(); + Object data = cs.getObject("p_out"); + assertEquals(data, dataPut, "Received data not equal to setdata"); + } } /** * Clean up + * + * @throws SQLException */ @AfterAll - public static void afterAll() { - try { - if (null != connection) { + public static void afterAll() throws SQLException { + try (Statement stmt = connection.createStatement()) { + Utils.dropProcedureIfExists("mystoredproc", stmt); + } + finally { + if (connection != null) { connection.close(); } - if (null != cs) { - cs.close(); - } - } - catch (SQLException e) { - fail(e.toString()); } } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java index 15fce3fe5..7d786dc46 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PQImpsTest.java @@ -30,6 +30,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerParameterMetaData; import com.microsoft.sqlserver.testframework.AbstractSQLGenerator; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; import com.microsoft.sqlserver.testframework.util.RandomUtil; /** @@ -1380,16 +1381,17 @@ public void testComplexQueryWithMultipleTables() throws SQLServerException { */ @AfterAll public static void dropTables() throws SQLException { - stmt.execute("if object_id('" + nameTable + "','U') is not null" + " drop table " + nameTable); - stmt.execute("if object_id('" + phoneNumberTable + "','U') is not null" + " drop table " + phoneNumberTable); - stmt.execute("if object_id('" + mergeNameDesTable + "','U') is not null" + " drop table " + mergeNameDesTable); - stmt.execute("if object_id('" + numericTable + "','U') is not null" + " drop table " + numericTable); - stmt.execute("if object_id('" + charTable + "','U') is not null" + " drop table " + charTable); - stmt.execute("if object_id('" + charTable2 + "','U') is not null" + " drop table " + charTable2); - stmt.execute("if object_id('" + binaryTable + "','U') is not null" + " drop table " + binaryTable); - stmt.execute("if object_id('" + dateAndTimeTable + "','U') is not null" + " drop table " + dateAndTimeTable); - stmt.execute("if object_id('" + multipleTypesTable + "','U') is not null" + " drop table " + multipleTypesTable); - stmt.execute("if object_id('" + spaceTable + "','U') is not null" + " drop table " + spaceTable); + Utils.dropTableIfExists(nameTable, stmt); + Utils.dropTableIfExists(phoneNumberTable, stmt); + Utils.dropTableIfExists(mergeNameDesTable, stmt); + Utils.dropTableIfExists(numericTable, stmt); + Utils.dropTableIfExists(phoneNumberTable, stmt); + Utils.dropTableIfExists(charTable, stmt); + Utils.dropTableIfExists(charTable2, stmt); + Utils.dropTableIfExists(binaryTable, stmt); + Utils.dropTableIfExists(dateAndTimeTable, stmt); + Utils.dropTableIfExists(multipleTypesTable, stmt); + Utils.dropTableIfExists(spaceTable, stmt); if (null != rs) { rs.close(); diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java index 626efeb99..7ce0773de 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/PoolableTest.java @@ -8,6 +8,7 @@ package com.microsoft.sqlserver.jdbc.unit.statement; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.sql.CallableStatement; import java.sql.Connection; @@ -16,6 +17,7 @@ import java.sql.SQLException; import java.sql.Statement; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; @@ -25,6 +27,7 @@ import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement; import com.microsoft.sqlserver.jdbc.SQLServerStatement; import com.microsoft.sqlserver.testframework.AbstractTest; +import com.microsoft.sqlserver.testframework.Utils; /** * Test Poolable statements @@ -35,44 +38,60 @@ public class PoolableTest extends AbstractTest { /** * Poolable Test + * * @throws SQLException * @throws ClassNotFoundException */ @Test @DisplayName("Poolable Test") - public void poolableTest() throws SQLException, ClassNotFoundException { - Connection connection = DriverManager.getConnection(connectionString); - Statement statement = connection.createStatement(); - try { - // First get the default values - boolean isPoolable = ((SQLServerStatement) statement).isPoolable(); - assertEquals(isPoolable, false, "SQLServerStatement should not be Poolable by default"); + public void poolableTest() throws SQLException, ClassNotFoundException { + try (Connection conn = DriverManager.getConnection(connectionString); Statement statement = conn.createStatement()) { + try { + // First get the default values + boolean isPoolable = ((SQLServerStatement) statement).isPoolable(); + assertEquals(isPoolable, false, "SQLServerStatement should not be Poolable by default"); - PreparedStatement prepStmt = connection.prepareStatement("select 1"); - isPoolable = ((SQLServerPreparedStatement) prepStmt).isPoolable(); - assertEquals(isPoolable, true, "SQLServerPreparedStatement should be Poolable by default"); + try (PreparedStatement prepStmt = connection.prepareStatement("select 1")) { + isPoolable = ((SQLServerPreparedStatement) prepStmt).isPoolable(); + assertEquals(isPoolable, true, "SQLServerPreparedStatement should be Poolable by default"); + } + try (CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }");) { + isPoolable = ((SQLServerCallableStatement) callableStatement).isPoolable(); - CallableStatement callableStatement = connection.prepareCall("{ ? = CALL " + "ProcName" + " (?, ?, ?, ?) }"); - isPoolable = ((SQLServerCallableStatement) callableStatement).isPoolable(); + assertEquals(isPoolable, true, "SQLServerCallableStatement should be Poolable by default"); - assertEquals(isPoolable, true, "SQLServerCallableStatement should be Poolable by default"); + // Now do couple of sets and gets - // Now do couple of sets and gets - - ((SQLServerCallableStatement) callableStatement).setPoolable(false); - assertEquals(((SQLServerCallableStatement) callableStatement).isPoolable(), false, "set did not work"); - callableStatement.close(); - - ((SQLServerStatement) statement).setPoolable(true); - assertEquals(((SQLServerStatement) statement).isPoolable(), true, "set did not work"); - statement.close(); + ((SQLServerCallableStatement) callableStatement).setPoolable(false); + assertEquals(((SQLServerCallableStatement) callableStatement).isPoolable(), false, "set did not work"); + } + ((SQLServerStatement) statement).setPoolable(true); + assertEquals(((SQLServerStatement) statement).isPoolable(), true, "set did not work"); + } + catch (UnsupportedOperationException e) { + assertEquals(System.getProperty("java.specification.version"), "1.5", "PoolableTest should be supported in anything other than 1.5"); + assertEquals(e.getMessage(), "This operation is not supported.", "Wrong exception message"); + } } - catch (UnsupportedOperationException e) { - assertEquals(System.getProperty("java.specification.version"), "1.5", "PoolableTest should be supported in anything other than 1.5"); - assertEquals(e.getMessage(), "This operation is not supported.", "Wrong exception message"); + } + + /** + * Clean up + * + * @throws Exception + */ + @AfterAll + public static void afterAll() throws Exception { + try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement()) { + try { + Utils.dropProcedureIfExists("ProcName", stmt); + } + catch (Exception ex) { + fail(ex.toString()); + } } - } - + } + } diff --git a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java index 715f1c457..afb311ae9 100644 --- a/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java +++ b/src/test/java/com/microsoft/sqlserver/jdbc/unit/statement/StatementTest.java @@ -1172,10 +1172,23 @@ public void testLargeMaxRowsJDBC42() throws Exception { } } + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { + try { + Utils.dropTableIfExists(table1Name, stmt); + Utils.dropTableIfExists(table2Name, stmt); + } + catch (SQLException e) { + } + } + } } @Nested public class TCStatementCallable { + String name = RandomUtil.getIdentifier("p1"); + String procName = AbstractSQLGenerator.escapeIdentifier(name); /** * Tests CallableStatementMethods on jdbc41 @@ -1187,41 +1200,19 @@ public void testJdbc41CallableStatementMethods() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Prepare database setup - String name = RandomUtil.getIdentifier("p1"); - String procName = AbstractSQLGenerator.escapeIdentifier(name); try (Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE)) { - String query = "create procedure " + procName - + " @col1Value varchar(512) OUTPUT," - + " @col2Value int OUTPUT," - + " @col3Value float OUTPUT," - + " @col4Value decimal(10,5) OUTPUT," - + " @col5Value uniqueidentifier OUTPUT," - + " @col6Value xml OUTPUT," - + " @col7Value varbinary(max) OUTPUT," - + " @col8Value text OUTPUT," - + " @col9Value ntext OUTPUT," - + " @col10Value varbinary(max) OUTPUT," - + " @col11Value date OUTPUT," - + " @col12Value time OUTPUT," - + " @col13Value datetime2 OUTPUT," - + " @col14Value datetimeoffset OUTPUT" - + " AS BEGIN " - + " SET @col1Value = 'hello'" - + " SET @col2Value = 1" - + " SET @col3Value = 2.0" - + " SET @col4Value = 123.45" - + " SET @col5Value = '6F9619FF-8B86-D011-B42D-00C04FC964FF'" - + " SET @col6Value = ''" - + " SET @col7Value = 0x63C34D6BCAD555EB64BF7E848D02C376" - + " SET @col8Value = 'text'" - + " SET @col9Value = 'ntext'" - + " SET @col10Value = 0x63C34D6BCAD555EB64BF7E848D02C376" - + " SET @col11Value = '2017-05-19'" - + " SET @col12Value = '10:47:15.1234567'" - + " SET @col13Value = '2017-05-19T10:47:15.1234567'" - + " SET @col14Value = '2017-05-19T10:47:15.1234567+02:00'" - + " END"; + String query = "create procedure " + procName + " @col1Value varchar(512) OUTPUT," + " @col2Value int OUTPUT," + + " @col3Value float OUTPUT," + " @col4Value decimal(10,5) OUTPUT," + " @col5Value uniqueidentifier OUTPUT," + + " @col6Value xml OUTPUT," + " @col7Value varbinary(max) OUTPUT," + " @col8Value text OUTPUT," + " @col9Value ntext OUTPUT," + + " @col10Value varbinary(max) OUTPUT," + " @col11Value date OUTPUT," + " @col12Value time OUTPUT," + + " @col13Value datetime2 OUTPUT," + " @col14Value datetimeoffset OUTPUT" + " AS BEGIN " + " SET @col1Value = 'hello'" + + " SET @col2Value = 1" + " SET @col3Value = 2.0" + " SET @col4Value = 123.45" + + " SET @col5Value = '6F9619FF-8B86-D011-B42D-00C04FC964FF'" + " SET @col6Value = ''" + + " SET @col7Value = 0x63C34D6BCAD555EB64BF7E848D02C376" + " SET @col8Value = 'text'" + " SET @col9Value = 'ntext'" + + " SET @col10Value = 0x63C34D6BCAD555EB64BF7E848D02C376" + " SET @col11Value = '2017-05-19'" + + " SET @col12Value = '10:47:15.1234567'" + " SET @col13Value = '2017-05-19T10:47:15.1234567'" + + " SET @col14Value = '2017-05-19T10:47:15.1234567+02:00'" + " END"; stmt.execute(query); // Test JDBC 4.1 methods for CallableStatement @@ -1244,7 +1235,7 @@ public void testJdbc41CallableStatementMethods() throws Exception { assertEquals("hello", cstmt.getObject(1, String.class)); assertEquals("hello", cstmt.getObject("col1Value", String.class)); - + assertEquals(Integer.valueOf(1), cstmt.getObject(2, Integer.class)); assertEquals(Integer.valueOf(1), cstmt.getObject("col2Value", Integer.class)); @@ -1256,7 +1247,7 @@ public void testJdbc41CallableStatementMethods() throws Exception { // BigDecimal#equals considers the number of decimal places assertEquals(0, cstmt.getObject(4, BigDecimal.class).compareTo(new BigDecimal("123.45"))); assertEquals(0, cstmt.getObject("col4Value", BigDecimal.class).compareTo(new BigDecimal("123.45"))); - + assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), cstmt.getObject(5, UUID.class)); assertEquals(UUID.fromString("6F9619FF-8B86-D011-B42D-00C04FC964FF"), cstmt.getObject("col5Value", UUID.class)); @@ -1264,16 +1255,18 @@ public void testJdbc41CallableStatementMethods() throws Exception { sqlXml = cstmt.getObject(6, SQLXML.class); try { assertEquals("", sqlXml.getString()); - } finally { + } + finally { sqlXml.free(); } Blob blob; blob = cstmt.getObject(7, Blob.class); try { - assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, 0x7E, (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, - blob.getBytes(1, 16)); - } finally { + assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, + 0x7E, (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, blob.getBytes(1, 16)); + } + finally { blob.free(); } @@ -1281,7 +1274,8 @@ public void testJdbc41CallableStatementMethods() throws Exception { clob = cstmt.getObject(8, Clob.class); try { assertEquals("text", clob.getSubString(1, 4)); - } finally { + } + finally { clob.free(); } @@ -1289,12 +1283,13 @@ public void testJdbc41CallableStatementMethods() throws Exception { nclob = cstmt.getObject(9, NClob.class); try { assertEquals("ntext", nclob.getSubString(1, 5)); - } finally { + } + finally { nclob.free(); } - assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, 0x7E, (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, - cstmt.getObject(10, byte[].class)); + assertArrayEquals(new byte[] {0x63, (byte) 0xC3, 0x4D, 0x6B, (byte) 0xCA, (byte) 0xD5, 0x55, (byte) 0xEB, 0x64, (byte) 0xBF, 0x7E, + (byte) 0x84, (byte) 0x8D, 0x02, (byte) 0xC3, 0x76}, cstmt.getObject(10, byte[].class)); assertEquals(java.sql.Date.valueOf("2017-05-19"), cstmt.getObject(11, java.sql.Date.class)); assertEquals(java.sql.Date.valueOf("2017-05-19"), cstmt.getObject("col11Value", java.sql.Date.class)); @@ -1307,18 +1302,29 @@ public void testJdbc41CallableStatementMethods() throws Exception { assertEquals("2017-05-19 10:47:15.1234567 +02:00", cstmt.getObject(14, microsoft.sql.DateTimeOffset.class).toString()); assertEquals("2017-05-19 10:47:15.1234567 +02:00", cstmt.getObject("col14Value", microsoft.sql.DateTimeOffset.class).toString()); - } finally { + } + } + } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { Utils.dropProcedureIfExists(procName, stmt); } + catch (SQLException e) { + fail(e.toString()); + } } } + } @Nested public class TCStatementParam { String tableNameTemp = RandomUtil.getIdentifier("TCStatementParam"); private final String tableName = AbstractSQLGenerator.escapeIdentifier(tableNameTemp); - String procNameTemp = RandomUtil.getIdentifier("p1"); + String procNameTemp = "TCStatementParam"; private final String procName = AbstractSQLGenerator.escapeIdentifier(procNameTemp); /** @@ -1339,9 +1345,8 @@ public void testStatementOutParamGetsTwice() throws Exception { log.fine("testStatementOutParamGetsTwice threw: " + e.getMessage()); } - Utils.dropProcedureIfExists("sp_ouputP", stmt); - stmt.executeUpdate( - "CREATE PROCEDURE [sp_ouputP] ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint RETURN @p2_smallint + 1"); + stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint RETURN @p2_smallint + 1"); ResultSet rs = stmt.getResultSet(); if (rs != null) { @@ -1351,7 +1356,7 @@ public void testStatementOutParamGetsTwice() throws Exception { else { assertEquals(stmt.isClosed(), false, "testStatementOutParamGetsTwice: statement should be open since no resultset."); } - CallableStatement cstmt = con.prepareCall("{ ? = CALL [sp_ouputP] (?,?)}"); + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1372,7 +1377,6 @@ public void testStatementOutParamGetsTwice() throws Exception { else { assertEquals((stmt).isClosed(), false, "testStatementOutParamGetsTwice: statement should be open since no resultset."); } - Utils.dropProcedureIfExists("sp_ouputP", stmt); } @Test @@ -1380,11 +1384,10 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - Utils.dropProcedureIfExists("sp_ouputMP", stmt); - stmt.executeUpdate( - "CREATE PROCEDURE [sp_ouputMP] ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT, @p4_smallint smallint OUTPUT, @p5_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint, @p5_smallint_out=@p4_smallint RETURN @p2_smallint + 1"); + stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT, @p4_smallint smallint OUTPUT, @p5_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p2_smallint, @p5_smallint_out=@p4_smallint RETURN @p2_smallint + 1"); - CallableStatement cstmt = con.prepareCall("{ ? = CALL [sp_ouputMP] (?,?, ?, ?)}"); + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?, ?, ?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("32"), Types.SMALLINT); cstmt.registerOutParameter(3, Types.SMALLINT); @@ -1401,8 +1404,6 @@ public void testStatementOutManyParamGetsTwiceRandomOrder() throws Exception { assertEquals(cstmt.getInt(3), 34, "Wrong value"); assertEquals(cstmt.getInt(5), 24, "Wrong value"); assertEquals(cstmt.getInt(1), 35, "Wrong value"); - - Utils.dropProcedureIfExists("sp_ouputMP", stmt); } /** @@ -1415,11 +1416,10 @@ public void testStatementOutParamGetsTwiceInOut() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement(); - Utils.dropProcedureIfExists("sp_ouputP", stmt); - stmt.executeUpdate( - "CREATE PROCEDURE [sp_ouputP] ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p3_smallint_out +1 RETURN @p2_smallint + 1"); + stmt.executeUpdate("CREATE PROCEDURE " + procNameTemp + + " ( @p2_smallint smallint, @p3_smallint_out smallint OUTPUT) AS SELECT @p3_smallint_out=@p3_smallint_out +1 RETURN @p2_smallint + 1"); - CallableStatement cstmt = con.prepareCall("{ ? = CALL [sp_ouputP] (?,?)}"); + CallableStatement cstmt = con.prepareCall("{ ? = CALL " + procNameTemp + " (?,?)}"); cstmt.registerOutParameter(1, Types.INTEGER); cstmt.setObject(2, Short.valueOf("1"), Types.SMALLINT); cstmt.setObject(3, Short.valueOf("100"), Types.SMALLINT); @@ -1432,8 +1432,6 @@ public void testStatementOutParamGetsTwiceInOut() throws Exception { cstmt.execute(); assertEquals(cstmt.getInt(1), 11, "Wrong value"); assertEquals(cstmt.getInt(3), 101, "Wrong value"); - - Utils.dropProcedureIfExists("sp_ouputP", stmt); } /** @@ -1447,18 +1445,6 @@ public void testResultSetParams() throws Exception { Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); @@ -1473,19 +1459,6 @@ public void testResultSetParams() throws Exception { rs.next(); assertEquals(rs.getString(2), "hello", "Wrong value"); assertEquals(cstmt.getString(2), "hi", "Wrong value"); - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; } /** @@ -1495,25 +1468,10 @@ public void testResultSetParams() throws Exception { */ @Test public void testResultSetNullParams() throws Exception { - String temp = RandomUtil.getIdentifier("RetestResultSetNullParams"); - String tableName = AbstractSQLGenerator.escapeIdentifier(temp); - Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); @@ -1531,19 +1489,6 @@ public void testResultSetNullParams() throws Exception { throw ex; } ; - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; } /** @@ -1555,12 +1500,7 @@ public void testFailedToResumeTransaction() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; + stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0)"); stmt.executeUpdate("Insert into " + tableName + " values(1)"); @@ -1581,12 +1521,6 @@ public void testFailedToResumeTransaction() throws Exception { } catch (SQLException ex) { } - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; conn.close(); } @@ -1600,18 +1534,6 @@ public void testResultSetErrors() throws Exception { Connection conn = DriverManager.getConnection(connectionString); Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int, col2 text, col3 int identity(1,1) primary key)"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hello')"); stmt.executeUpdate("Insert into " + tableName + " values(0, 'hi')"); @@ -1631,45 +1553,20 @@ public void testResultSetErrors() throws Exception { ; assertEquals(null, cstmt.getString(2), "Wrong value"); - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; } /** * Verify proper handling of row errors in ResultSets. */ @Test - @Disabled - //TODO: We are commenting this out due to random AppVeyor failures. We will investigate later. + @Disabled + // TODO: We are commenting this out due to random AppVeyor failures. We will investigate later. public void testRowError() throws Exception { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(connectionString); // Set up everything Statement stmt = conn.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.executeUpdate("create table " + tableName + " (col1 int primary key)"); stmt.executeUpdate("insert into " + tableName + " values(0)"); @@ -1757,22 +1654,22 @@ public void testRowError() throws Exception { testConn2.close(); testConn1.close(); } - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (Exception ex) { - } - ; - try { - Utils.dropProcedureIfExists(procName, stmt); - } - catch (Exception ex) { - } - ; stmt.close(); conn.close(); } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + Utils.dropProcedureIfExists(procName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } + } + } } @Nested @@ -1790,11 +1687,6 @@ private Connection createConnectionAndPopulateData() throws Exception { con = ds.getConnection(); Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - } stmt.executeUpdate("CREATE TABLE " + tableName + "(col1_int int PRIMARY KEY IDENTITY(1,1), col2_varchar varchar(200), col3_varchar varchar(20) SPARSE NULL, col4_smallint smallint SPARSE NULL, col5_xml XML COLUMN_SET FOR ALL_SPARSE_COLUMNS, col6_nvarcharMax NVARCHAR(MAX), col7_varcharMax VARCHAR(MAX))"); @@ -1804,19 +1696,15 @@ private Connection createConnectionAndPopulateData() throws Exception { return con; } - private void cleanup(Connection con) throws Exception { - try { - if (con == null || con.isClosed()) { - con = DriverManager.getConnection(connectionString); + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + fail(e.toString()); } - - Utils.dropTableIfExists(tableName, con.createStatement()); - } - catch (SQLException e) { - } - finally { - if (con != null) - con.close(); } } @@ -1849,7 +1737,7 @@ public void testNBCROWNullsForLOBs() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -1891,7 +1779,7 @@ public void testSparseColumnSetValues() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -1934,7 +1822,7 @@ public void testSparseColumnSetIndex() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -1946,66 +1834,64 @@ public void testSparseColumnSetIndex() throws Exception { */ @Test public void testSparseColumnSetForException() throws Exception { - if (new DBConnection(connectionString).getServerVersion() <= 9.0) { - log.fine("testSparseColumnSetForException skipped for Yukon"); + try (DBConnection conn = new DBConnection(connectionString)) { + if (conn.getServerVersion() <= 9.0) { + log.fine("testSparseColumnSetForException skipped for Yukon"); + } } - Connection con = null; - try { - con = createConnectionAndPopulateData(); - Statement stmt = con.createStatement(); - // enable isCloseOnCompletion - try { - stmt.closeOnCompletion(); - } - catch (Exception e) { + con = createConnectionAndPopulateData(); + Statement stmt = con.createStatement(); - throw new SQLException("testSparseColumnSetForException threw exception: ", e); + // enable isCloseOnCompletion + try { + stmt.closeOnCompletion(); + } + catch (Exception e) { - } + throw new SQLException("testSparseColumnSetForException threw exception: ", e); - String selectQuery = "SELECT * FROM " + tableName; - ResultSet rs = stmt.executeQuery(selectQuery); - rs.next(); + } - SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - try { - // test that an exception is thrown when result set is closed - rs.close(); - rsmd.isSparseColumnSet(1); - assertEquals(true, false, "Should not reach here. An exception should have been thrown"); - } - catch (SQLException e) { - } + String selectQuery = "SELECT * FROM " + tableName; + ResultSet rs = stmt.executeQuery(selectQuery); + rs.next(); - // test that an exception is thrown when statement is closed - try { - rs = stmt.executeQuery(selectQuery); - rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + SQLServerResultSetMetaData rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + try { + // test that an exception is thrown when result set is closed + rs.close(); + rsmd.isSparseColumnSet(1); + assertEquals(true, false, "Should not reach here. An exception should have been thrown"); + } + catch (SQLException e) { + } - assertEquals(stmt.isClosed(), true, "testSparseColumnSetForException: statement should be closed since resultset is closed."); - stmt.close(); - rsmd.isSparseColumnSet(1); - assertEquals(true, false, "Should not reach here. An exception should have been thrown"); - } - catch (SQLException e) { - } + // test that an exception is thrown when statement is closed + try { + rs = stmt.executeQuery(selectQuery); + rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - // test that an exception is thrown when connection is closed - try { - rs = con.createStatement().executeQuery("SELECT * FROM " + tableName); - rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); - con.close(); - rsmd.isSparseColumnSet(1); - assertEquals(true, false, "Should not reach here. An exception should have been thrown"); - } - catch (SQLException e) { - } + assertEquals(stmt.isClosed(), true, "testSparseColumnSetForException: statement should be closed since resultset is closed."); + stmt.close(); + rsmd.isSparseColumnSet(1); + assertEquals(true, false, "Should not reach here. An exception should have been thrown"); } - finally { - cleanup(con); + catch (SQLException e) { + } + + // test that an exception is thrown when connection is closed + try { + rs = con.createStatement().executeQuery("SELECT * FROM " + tableName); + rsmd = (SQLServerResultSetMetaData) rs.getMetaData(); + con.close(); + rsmd.isSparseColumnSet(1); + assertEquals(true, false, "Should not reach here. An exception should have been thrown"); } + catch (SQLException e) { + } + } /** @@ -2053,7 +1939,7 @@ public void testNBCRowForAllNulls() throws Exception { } finally { - cleanup(con); + terminate(); } } @@ -2159,7 +2045,7 @@ public void testNBCROWWithRandomAccess() throws Exception { } } finally { - cleanup(con); + terminate(); } } @@ -2376,24 +2262,7 @@ private void setup() throws Exception { Connection con = DriverManager.getConnection(connectionString); con.setAutoCommit(false); Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - throw new SQLException(e); - } - try { - Utils.dropTableIfExists(table2Name, stmt); - } - catch (SQLException e) { - throw new SQLException(e); - } - try { - Utils.dropProcedureIfExists(sprocName, stmt); - } - catch (SQLException e) { - throw new SQLException(e); - } + try { stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName + "') drop trigger " + triggerName); } @@ -2499,6 +2368,20 @@ public void testStatementInsertExecInsert() throws Exception { // which should have affected 1 (new) row in tableName. assertEquals(updateCount, 1, "Wrong update count"); } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { + try { + Utils.dropTableIfExists(tableName, stmt); + Utils.dropTableIfExists(table2Name, stmt); + Utils.dropProcedureIfExists(sprocName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } + } + } } @Nested @@ -2514,11 +2397,7 @@ private void setup() throws Exception { Connection con = DriverManager.getConnection(connectionString); con.setAutoCommit(false); Statement stmt = con.createStatement(); - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - } + try { stmt.executeUpdate("if EXISTS (SELECT * FROM sys.triggers where name = '" + triggerName + "') drop trigger " + triggerName); } @@ -2704,6 +2583,18 @@ public void testUpdateCountAfterErrorInTriggerLastUpdateCountTrue() throws Excep pstmt.close(); con.close(); } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement();) { + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } + } + } } @Nested @@ -2728,12 +2619,6 @@ private void setup() throws Exception { throw new SQLException("setup threw exception: ", e); } - - try { - Utils.dropTableIfExists(tableName, stmt); - } - catch (SQLException e) { - } stmt.executeUpdate("CREATE TABLE " + tableName + " (col1 INT primary key)"); for (int i = 0; i < NUM_ROWS; i++) stmt.executeUpdate("INSERT INTO " + tableName + " (col1) VALUES (" + i + ")"); @@ -2752,26 +2637,36 @@ private void setup() throws Exception { @Test public void testNoCountWithExecute() throws Exception { // Ensure lastUpdateCount=true... - Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); - Statement stmt = con.createStatement(); - boolean isResultSet = stmt - .execute("set nocount on\n" + "insert into " + tableName + "(col1) values(" + (NUM_ROWS + 1) + ")\n" + "select 1"); + try (Connection con = DriverManager.getConnection(connectionString + ";lastUpdateCount = true"); + Statement stmt = con.createStatement();) { - assertEquals(true, isResultSet, "execute() said first result was an update count"); + boolean isResultSet = stmt + .execute("set nocount on\n" + "insert into " + tableName + "(col1) values(" + (NUM_ROWS + 1) + ")\n" + "select 1"); - ResultSet rs = stmt.getResultSet(); - while (rs.next()) - ; - rs.close(); + assertEquals(true, isResultSet, "execute() said first result was an update count"); - boolean moreResults = stmt.getMoreResults(); - assertEquals(false, moreResults, "next result is a ResultSet?"); + ResultSet rs = stmt.getResultSet(); + while (rs.next()); + rs.close(); - int updateCount = stmt.getUpdateCount(); - assertEquals(-1, updateCount, "only one result was expected..."); + boolean moreResults = stmt.getMoreResults(); + assertEquals(false, moreResults, "next result is a ResultSet?"); - stmt.close(); - con.close(); + int updateCount = stmt.getUpdateCount(); + assertEquals(-1, updateCount, "only one result was expected..."); + } + } + + @AfterEach + public void terminate() throws Exception { + try (Connection con = DriverManager.getConnection(connectionString); Statement stmt = con.createStatement()) { + try { + Utils.dropTableIfExists(tableName, stmt); + } + catch (SQLException e) { + fail(e.toString()); + } + } } } } diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java index 51e0c7aa2..a6ae11d07 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBConnection.java @@ -21,7 +21,7 @@ /* * Wrapper class for SQLServerConnection */ -public class DBConnection extends AbstractParentWrapper { +public class DBConnection extends AbstractParentWrapper implements AutoCloseable { private double serverversion = 0; // TODO: add Isolation Level diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java index 0851f3907..d281effca 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBResultSet.java @@ -36,7 +36,7 @@ * */ -public class DBResultSet extends AbstractParentWrapper { +public class DBResultSet extends AbstractParentWrapper implements AutoCloseable { // TODO: add cursors // TODO: add resultSet level holdability diff --git a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java index 8d4787120..00b006026 100644 --- a/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java +++ b/src/test/java/com/microsoft/sqlserver/testframework/DBStatement.java @@ -21,7 +21,7 @@ * @author Microsoft * */ -public class DBStatement extends AbstractParentWrapper { +public class DBStatement extends AbstractParentWrapper implements AutoCloseable{ // TODO: support PreparedStatement and CallableStatement // TODO: add stmt level holdability @@ -120,7 +120,7 @@ public void close() throws SQLException { if ((null != dbresultSet) && null != ((ResultSet) dbresultSet.product())) { ((ResultSet) dbresultSet.product()).close(); } - statement.close(); + //statement.close(); } /**