public void test_batchInsert_unique_constraint_OriginalException() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); { Member member = new Member(); member.setMemberName("testName1"); member.setMemberAccount("testAccount1"); member.setMemberStatusCode_Formalized(); // 正式会員 memberList.add(member); } { Member member = new Member(); member.setMemberName("testName2"); member.setMemberAccount("testAccount2"); member.setMemberStatusCode_Formalized(); // 正式会員 memberList.add(member); } // ## Act & Assert ## memberBhv.batchInsert(memberList); try { memberBhv.batchInsert(memberList); fail(); } catch (EntityAlreadyExistsException e) { SQLException cause = e.getSQLException(); log(e.getMessage()); log("/* * * * * * * * * * * * * * * * *"); log("SQLState=" + cause.getSQLState() + ", ErrorCode=" + cause.getErrorCode()); log("* * * * * * * * * */"); assertEquals(MY_SQLSTATE, cause.getSQLState()); assertEquals(MY_ERRORCODE, cause.getErrorCode()); } }
protected void applySecurityToGFE(Connection gConn, String sql) { Log.getLogWriter().info("execute authorization statement in GFE"); Log.getLogWriter().info("security statement is: " + sql); try { Statement stmt = gConn.createStatement(); stmt.execute(sql); // execute authorization } catch (SQLException se) { if (se.getSQLState().equals("42506") && SQLTest.testSecurity) Log.getLogWriter() .info("Got the expected exception for authorization," + " continuing tests"); else if (se.getSQLState().equals("42509") && SQLTest.testSecurity) Log.getLogWriter() .info( "Got the expected grant or revoke operation " + "is not allowed exception for authorization," + " continuing tests"); else if (se.getSQLState().equals("42Y03") && hasRoutine) Log.getLogWriter() .info( "Got the expected not recognized as " + "a function or procedure exception for authorization," + " continuing tests"); else SQLHelper.handleSQLException(se); } }
public void test_batchUpdateNonstrict_unique_constraint_OriginalException() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); { Member member = memberBhv.selectByPKValueWithDeletedCheck(memberIdTwo); member.setMemberAccount("AAA"); memberList.add(member); } { Member member = memberBhv.selectByPKValueWithDeletedCheck(memberIdThree); member.setMemberAccount("Pixy"); memberList.add(member); } // ## Act & Assert ## try { memberBhv.batchUpdateNonstrict(memberList); fail(); } catch (EntityAlreadyExistsException e) { SQLException cause = e.getSQLException(); log(e.getMessage()); log("/* * * * * * * * * * * * * * * * *"); log("SQLState=" + cause.getSQLState() + ", ErrorCode=" + cause.getErrorCode()); log("* * * * * * * * * */"); assertEquals(MY_SQLSTATE, cause.getSQLState()); assertEquals(MY_ERRORCODE, cause.getErrorCode()); } }
/** Test on kinds of database names. */ public void testDBName() throws SQLException { // Do we get a non-internal error when we try to create // over an existing directory? (T#674) String url = "jdbc:splice:wombat/seg0;create=true"; try { DriverManager.getConnection(url); fail("Error XBM0J is expected"); } catch (SQLException e) { assertEquals("XJ041", e.getSQLState()); } // -- check to ensure an empty database name is taken // -- as the name, over any connection attribute. // -- this should fail. url = "jdbc:splice: ;databaseName=wombat"; try { DriverManager.getConnection(url); fail("Error XJ004 is expected"); } catch (SQLException e) { assertEquals("XJ004", e.getSQLState()); } // and this should succeed (no database name in URL) url = "jdbc:splice:;databaseName=wombat"; Connection con = DriverManager.getConnection(url); con.close(); }
/** * Doing some simple grant/revoke negative tests in legacy database. All should fail with errors. */ public void testGrantAndRevoke() throws SQLException { String url = "jdbc:splice:wombat"; Connection con = DriverManager.getConnection(url); String sql = "create table mytab(i int)"; Statement st = con.createStatement(); st.execute(sql); sql = "grant select on mytab to satheesh"; try { st.executeUpdate(sql); fail("Error 42Z60 is expected"); } catch (SQLException e) { assertEquals("42Z60", e.getSQLState()); } sql = "revoke select on mytab to satheesh"; try { st.executeUpdate(sql); fail("Error 42Z60 is expected"); } catch (SQLException e) { assertEquals("42Z60", e.getSQLState()); } sql = "drop table mytab"; st.execute(sql); st.close(); con.close(); }
public DataBaseManagement(String driver, String dbURL) { try { this.dbURL = dbURL; Class.forName(driver).newInstance(); conn = DriverManager.getConnection(dbURL); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block if (e instanceof SQLException) { SQLException sqle = (SQLException) e; if (sqle.getSQLState().equals("XJ040")) { sqle = sqle.getNextException(); if (sqle.getSQLState().equals("XSDB6")) { logger.error(sqle.getMessage() + " Please shutdown that other instance of Derby."); } } } else { CustomException.errorPrint(e); } } }
/** * 例外チェーンをたどって原因となった{@link SQLException#getSQLState() SQLステート}を返します。 * * <p>例外チェーンに{@link SQLException SQL例外}が存在しない場合や、SQLステートが設定されていない場合は <code>null</code>を返します。 * * @param t 例外 * @return 原因となった{@link SQLException#getSQLState() SQLステート} */ protected String getSQLState(Throwable t) { SQLException cause = getCauseSQLException(t); if (cause != null && !StringUtil.isEmpty(cause.getSQLState())) { return cause.getSQLState(); } return null; }
protected boolean test(Statement aStatement) { try { aStatement.execute(getSql()); } catch (SQLException sqlX) { caught = sqlX; if (expectedState == null || expectedState.equalsIgnoreCase(sqlX.getSQLState())) { return true; } message = "SQLState '" + sqlX.getSQLState() + "' instead of '" + expectedState + "': " + sqlX.getMessage(); } catch (Exception x) { caught = x; message = x.getMessage(); } return false; }
public <ResultType> ResultType doExecuteTransaction(Transaction<ResultType> txn) throws SQLException { Connection conn = connect(); try { int numAttempts = 0; boolean success = false; ResultType result = null; while (!success && numAttempts < MAX_ATTEMPTS) { try { result = txn.execute(conn); conn.commit(); success = true; } catch (SQLException e) { if (e.getSQLState() != null && e.getSQLState().equals("41000")) { // Deadlock: retry (unless max retry count has been reached) numAttempts++; } else { // Some other kind of SQLException throw e; } } } if (!success) { throw new SQLException("Transaction failed (too many retries)"); } // Success! return result; } finally { DBUtil.closeQuietly(conn); } }
public void testBug45897() throws Exception { // Test DROP DISKSTORE on default diskstore names (should throw sqlstate 0A000) // Default diskstore names have embedded hyphens and therefore need delimiting w/quotes try { Connection conn; conn = TestUtil.getConnection(); Statement stmt = conn.createStatement(); // Try to drop the default diskstore. Should fail with 0A000. stmt.execute("Drop DiskStore " + "\"" + GfxdConstants.GFXD_DD_DISKSTORE_NAME + "\""); fail("Disk store drop should fail because diskstore is a default one"); } catch (SQLException e) { assertEquals(e.getSQLState(), "0A000"); } // Try the other named default diskstore try { Connection conn; conn = TestUtil.getConnection(); Statement stmt = conn.createStatement(); // Try to drop the default diskstore. Should fail with 0A000. stmt.execute("Drop DiskStore " + "\"" + GfxdConstants.GFXD_DEFAULT_DISKSTORE_NAME + "\""); fail("Disk store drop should fail because diskstore is a default one"); } catch (SQLException e) { assertEquals(e.getSQLState(), "0A000"); } }
/* (non-Javadoc) * @see org.datanucleus.store.rdbms.adapter.DatabaseAdapter#isStatementTimeout(java.sql.SQLException) */ @Override public boolean isStatementTimeout(SQLException sqle) { if (sqle.getSQLState() != null && sqle.getSQLState().equalsIgnoreCase("HY008")) { return true; } return super.isStatementTimeout(sqle); }
/** * Gets the SQL state code from the supplied {@link SQLException exception}. * * <p>Some JDBC drivers nest the actual exception from a batched update, so we might need to dig * down into the nested exception. * * @param ex the exception from which the {@link SQLException#getSQLState() SQL state} is to be * extracted * @return the SQL state code */ private String getSqlState(SQLException ex) { String sqlState = ex.getSQLState(); if (sqlState == null) { SQLException nestedEx = ex.getNextException(); if (nestedEx != null) { sqlState = nestedEx.getSQLState(); } } return sqlState; }
/** * Shutdown the datbase * * @param dbName Name of the database to shutdown. */ void shutdown(String dbName) { try { // shutdown TestUtil.getConnection(dbName, "shutdown=true"); } catch (SQLException se) { if (se.getSQLState() != null && se.getSQLState().equals("08006")) System.out.println("database shutdown properly"); else dumpSQLException(se); } }
/** Shutdown the datbase */ void shutdown() { if (verbose) logMessage("Shutdown " + currentTestDatabase); try { // shutdown TestUtil.getConnection(currentTestDatabase, "shutdown=true"); } catch (SQLException se) { if (se.getSQLState() == null || !(se.getSQLState().equals("08006"))) { // database was not shutdown properly dumpSQLException(se); } } }
/** * * Test SSL client with non-SSL server fails * * @throws Exception */ @Test public void testInvalidConfig() throws Exception { clearSslConfOverlay(confOverlay); // Test in binary mode setBinaryConfOverlay(confOverlay); miniHS2.start(confOverlay); DriverManager.setLoginTimeout(4); try { hs2Conn = DriverManager.getConnection( miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar"); fail("SSL connection should fail with NON-SSL server"); } catch (SQLException e) { // expected error assertEquals("08S01", e.getSQLState().trim()); } System.setProperty(JAVA_TRUST_STORE_PROP, dataFileDir + File.separator + TRUST_STORE_NAME); System.setProperty(JAVA_TRUST_STORE_PASS_PROP, KEY_STORE_PASSWORD); try { hs2Conn = DriverManager.getConnection( miniHS2.getJdbcURL() + ";ssl=true", System.getProperty("user.name"), "bar"); fail("SSL connection should fail with NON-SSL server"); } catch (SQLException e) { // expected error assertEquals("08S01", e.getSQLState().trim()); } miniHS2.stop(); // Test in http mode with ssl properties specified in url System.clearProperty(JAVA_TRUST_STORE_PROP); System.clearProperty(JAVA_TRUST_STORE_PASS_PROP); setHttpConfOverlay(confOverlay); miniHS2.start(confOverlay); try { hs2Conn = DriverManager.getConnection( miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar"); fail("SSL connection should fail with NON-SSL server"); } catch (SQLException e) { // expected error assertEquals("08S01", e.getSQLState().trim()); } }
/** * Create table in database. <br> * * @throws ProvMonitorException If table could not be created. <br> * @throws DatabaseException <code>Database related problems.</code><br> * <ul> * <li>ConnectionException - Connection problems related. * <li>DatabaseException - Problems with the table creation itself. * </ul> */ @Override public void createTable() throws ProvMonitorException { Connection conn = ConnectionManager.getInstance().getConnection(); Statement s = null; try { try { // Preparing statement s = conn.createStatement(); // Transaction control conn.setAutoCommit(false); } catch (SQLException e) { throw new ConnectionException(e.getMessage(), e.getCause(), e.getSQLState()); } if (s != null) { String createTableSQL = "CREATE TABLE PROCESS_INSTANCE (INSTANCE_ID VARCHAR(255) NOT NULL" + ", PROCESS_ID VARCHAR(255) NOT NULL" + ", NAME VARCHAR(255)" + ", SWFMS_ID INT" + ")"; s.executeUpdate(createTableSQL); conn.commit(); } } catch (SQLException e) { try { conn.rollback(); } catch (SQLException ex) { } throw new DatabaseException(e.getMessage(), e.getCause()); } }
/** * Verify table existence in database. <br> * * @return <code><b>true</b></code> - If table exists. <br> * <code><b>false</b></code> - If table does not exist. * @throws ProvMonitorException If table could not be created. <br> */ @Override public boolean isTableCreated() throws ProvMonitorException { Connection conn = ConnectionManager.getInstance().getConnection(); try { try { // Transaction control conn.setAutoCommit(false); } catch (SQLException e) { throw new ConnectionException(e.getMessage(), e.getCause(), e.getSQLState()); } // Verifying schema PreparedStatement psInsert = conn.prepareStatement( "INSERT INTO PROCESS_INSTANCE (INSTANCE_ID, PROCESS_ID) values (?,?)"); psInsert.setString(1, "TesteParam1"); psInsert.setString(2, "TesteParam2"); psInsert.executeUpdate(); conn.rollback(); return true; } catch (SQLException e) { // Schema object does not exist try { conn.rollback(); } catch (SQLException ex) { } return false; } }
public static void insertSingleKeyTable(String tableName, int pk1) throws SQLException { Connection conn = getDefaultConnection(); PreparedStatement ps = conn.prepareStatement(insertsql); ps.setString(1, tableName); ps.setInt(2, pk1); ps.setInt(3, -1); ps.setInt(4, 1); ps.setInt(5, 0); ps.setInt(6, 0); Log.getLogWriter() .info("insert into trade.monitor values(" + tableName + ", " + pk1 + ", -1, 1, 0, 0 )"); try { ps.execute(); } catch (SQLException se) { if (se.getSQLState().equals("X0Z02")) { throw new TestException( "Got unexpected conflict exception in trigger" + TestHelper.getStackTrace(se)); } else throw se; } closeConnection(conn); }
public static void deleteTxhistory(String tableName, int pk1, String type) throws SQLException { Connection conn = getDefaultConnection(); int pk2 = type.equalsIgnoreCase("sell") ? SELL : BUY; String deletgfxdTxhistory = "update trade.monitor set deleteCount = deleteCount + 1 " + "where tname = ? and pk1 = ? and pk2 = ?"; PreparedStatement ps = conn.prepareStatement(deletgfxdTxhistory); ps.setString(1, tableName); ps.setInt(2, pk1); ps.setInt(3, pk2); Log.getLogWriter() .info(deletgfxdTxhistory + " for " + tableName + " and pk1 " + pk1 + " and pk2 " + pk2); try { ps.execute(); } catch (SQLException se) { if (se.getSQLState().equals("X0Z02")) { throw new TestException( "Got unexpected conflict exception in trigger" + TestHelper.getStackTrace(se)); } else throw se; } closeConnection(conn); }
public static void updatePortfolio(String tableName, int pk1, int pk2) throws SQLException { Connection conn = getDefaultConnection(); String updatgfxdPortfolio = "update trade.monitor set updateCount = updateCount + 1 " + "where tname = ? and pk1 = ? and pk2 = ?"; PreparedStatement ps = conn.prepareStatement(updatgfxdPortfolio); ps.setString(1, tableName); ps.setInt(2, pk1); ps.setInt(3, pk2); Log.getLogWriter() .info(updatgfxdPortfolio + " for " + tableName + " and pk1 " + pk1 + " and pk2 " + pk2); try { ps.execute(); } catch (SQLException se) { if (se.getSQLState().equals("X0Z02")) { throw new TestException( "Got unexpected conflict exception in trigger" + TestHelper.getStackTrace(se)); } else throw se; } closeConnection(conn); }
@Override public void Insert(UsersFriends usersFriends) { // SQL // INSERT INTO UsersFriends (VkID_User, VkID_Friend) VALUES (usersFriends.getVkIDUser(), // usersFriends.getVkIDFriend()); String SQL = ""; try { this.dbHandler.openConnection(); Statement statement = this.dbHandler.getConnection().createStatement(); SQL = "INSERT INTO UsersFriends (VkID_User, VkID_Friend) VALUES (\"" + usersFriends.getVkIDUser() + "\",\"" + usersFriends.getVkIDFriend() + "\")"; statement.executeUpdate(SQL); } catch (SQLException ex) { System.out.println("SQLException caught"); System.out.println("---"); while (ex != null) { System.out.println("Message : " + ex.getMessage()); System.out.println("SQLState : " + ex.getSQLState()); System.out.println("ErrorCode : " + ex.getErrorCode()); System.out.println("---"); ex = ex.getNextException(); } } catch (Exception ex) { System.out.println("Other Error in Main."); } }
public int selectIntSumByUID(String colName, String table, int uid) { // Make the statement. String stmt = "SELECT `" + colName + "` FROM `" + table + "` WHERE `" + table + "`.`uid` = " + uid + ";"; // Do the query. try { int currentSum = 0; Statement dbStmt = dbConnection.createStatement(); if (dbStmt.execute(stmt)) { ResultSet dbResultSet = dbStmt.getResultSet(); while (dbResultSet.next()) { currentSum += dbResultSet.getInt(1); } return currentSum; } else { System.err.println("CustomCommunication.selectSingleByUID failed"); } return -1; } catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); return -1; } }
private void putUpdateStoredBlock(StoredBlock storedBlock, boolean wasUndoable) throws SQLException { try { PreparedStatement s = conn.get() .prepareStatement( "INSERT INTO headers(hash, chainWork, height, header, wasUndoable)" + " VALUES(?, ?, ?, ?, ?)"); // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes byte[] hashBytes = new byte[28]; System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28); s.setBytes(1, hashBytes); s.setBytes(2, storedBlock.getChainWork().toByteArray()); s.setInt(3, storedBlock.getHeight()); s.setBytes(4, storedBlock.getHeader().unsafeRimbitSerialize()); s.setBoolean(5, wasUndoable); s.executeUpdate(); s.close(); } catch (SQLException e) { // It is possible we try to add a duplicate StoredBlock if we upgraded // In that case, we just update the entry to mark it wasUndoable if (!(e.getSQLState().equals(POSTGRES_DUPLICATE_KEY_ERROR_CODE)) || !wasUndoable) throw e; PreparedStatement s = conn.get().prepareStatement("UPDATE headers SET wasUndoable=? WHERE hash=?"); s.setBoolean(1, true); // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes byte[] hashBytes = new byte[28]; System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28); s.setBytes(2, hashBytes); s.executeUpdate(); s.close(); } }
// for portfolio and txhistory private static void newlyInsertedTable(Connection conn, String tableName, int pk1, int pk2) throws SQLException { PreparedStatement ps = conn.prepareStatement(insertsql); ps.setString(1, tableName); ps.setInt(2, pk1); ps.setInt(3, pk2); ps.setInt(4, 1); ps.setInt(5, 0); ps.setInt(6, 0); Log.getLogWriter() .info( "insert into trade.monitor values(" + tableName + ", " + pk1 + ", " + pk2 + ", 1, 0, 0 )"); try { ps.execute(); } catch (SQLException se) { if (se.getSQLState().equals("X0Z02")) { throw new TestException( "Got unexpected conflict exception in trigger" + TestHelper.getStackTrace(se)); } else throw se; } }
/** * Takes a columnName, a tableName and a userID, and does "SELECT colName FROM table WHERE * table.`uid` = userID". * * @param colName * @param table * @param uid * @return The first double from the ResultSet of the query. -1.0 if failed. */ public double selectSingleDoubleByUID(String colName, String table, int uid) { // Make the statement. String stmt = "SELECT `" + colName + "` FROM `" + table + "` WHERE `" + table + "`.`uid` = " + uid + ";"; // Do the query. try { Statement dbStmt = dbConnection.createStatement(); ResultSet dbResultSet = null; if (dbStmt.execute(stmt)) { dbResultSet = dbStmt.getResultSet(); dbResultSet.last(); return dbResultSet.getDouble(1); } else { System.err.println("CustomCommunication.selectSingleByUID failed"); } return -1.0; } catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); return -1.0; } }
public static void CloseDbConnection(Connection conn) { try { // shut down the database conn.close(); System.out.println("Closed connection"); /* In embedded mode, an application should shut down Derby. Shutdown throws the XJ015 exception to confirm success. */ boolean gotSQLExc = false; try { DriverManager.getConnection("jdbc:derby:;shutdown=true"); DriverManager.getConnection("exit"); } catch (SQLException se) { if (se.getSQLState().equals("XJ015")) { gotSQLExc = true; } } if (!gotSQLExc) { System.out.println("Database did not shut down normally"); } else { System.out.println("Database shut down normally"); } // force garbage collection to unload the EmbeddedDriver // so Derby can be restarted System.gc(); } catch (Throwable e) { System.out.println(e); ; System.exit(1); } }
private void sendError(Throwable t) { try { SQLException e = DbException.convert(t).getSQLException(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String trace = writer.toString(); String message; String sql; if (e instanceof JdbcSQLException) { JdbcSQLException j = (JdbcSQLException) e; message = j.getOriginalMessage(); sql = j.getSQL(); } else { message = e.getMessage(); sql = null; } transfer .writeInt(SessionRemote.STATUS_ERROR) .writeString(e.getSQLState()) .writeString(message) .writeString(sql) .writeInt(e.getErrorCode()) .writeString(trace) .flush(); } catch (Exception e2) { if (!transfer.isClosed()) { server.traceError(e2); } // if writing the error does not work, close the connection stop = true; } }
@Override public void handleRetryException(SQLException sqlException) throws RetryTransactionException { if (sqlException instanceof BatchUpdateException && Arrays.binarySearch(BATCH_UPDATE_RETRY_CODES, sqlException.getSQLState()) >= 0) { throw new RetryTransactionException(sqlException); } }
private List<UsersFriends> FindBy(String SQL) { List<UsersFriends> usersFriendsList = new ArrayList<UsersFriends>(); try { this.dbHandler.openConnection(); Statement statement = this.dbHandler.getConnection().createStatement(); ResultSet result = statement.executeQuery(SQL); while (result.next()) { usersFriendsList.add( new UsersFriends( result.getInt("id"), result.getInt("id_user"), result.getInt("id_friend"))); } // else System.out.println("Записи с данными параметрами не существует"); } catch (SQLException ex) { System.out.println("SQLException caught"); System.out.println("---"); while (ex != null) { System.out.println("Message : " + ex.getMessage()); System.out.println("SQLState : " + ex.getSQLState()); System.out.println("ErrorCode : " + ex.getErrorCode()); System.out.println("---"); ex = ex.getNextException(); } } catch (Exception ex) { System.out.println("Other Error in Main."); } return usersFriendsList; }
public void testBug42750() throws Exception { Properties props = new Properties(); Connection conn = TestUtil.getConnection(props); char fileSeparator = System.getProperty("file.separator").charAt(0); Misc.getGemFireCache(); conn.createStatement(); String path = "." + fileSeparator + "test_dir"; File file = new File(path); if (!file.mkdirs() && !file.isDirectory()) { throw new DiskAccessException( "Could not create directory for " + " default disk store : " + file.getAbsolutePath(), (Region) null); } try { Connection conn1; conn1 = TestUtil.getConnection(); Statement stmt1 = conn1.createStatement(); stmt1.execute("Create DiskStore " + "TestPersistenceDiskStore" + "'" + path + "'"); conn1.close(); TestUtil.shutDown(); conn1 = TestUtil.getConnection(); stmt1 = conn1.createStatement(); stmt1.execute("Create DiskStore " + "TestPersistenceDiskStore" + "'" + path + "'"); fail("Disk store creation should fail as the disk store already exists"); } catch (SQLException e) { assertEquals(e.getSQLState(), "X0Y68"); } }