List of usage examples for java.sql SQLException getSQLState
public String getSQLState()
SQLException
object. From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
/** * Attempts to read the first 10 records from a given report, to check there * isn't an error in the SQL/*w w w. j a va 2 s . c o m*/ */ private void throwExceptionIfDbViewIsBroken(Connection conn, BaseReportInfo report) throws SQLException, ObjectNotFoundException, CodingErrorException, CantDoThatException { PreparedStatement statement = null; try { ReportData.enableOptimisations(conn, report, true); String SQLCode = "SELECT * FROM " + report.getInternalReportName() + " LIMIT 10"; statement = conn.prepareStatement(SQLCode); ResultSet testResults = statement.executeQuery(); ResultSetMetaData metaData = testResults.getMetaData(); int numColumns = metaData.getColumnCount(); while (testResults.next()) { for (int i = 1; i <= numColumns; i++) { String testKey = testResults.getString(i); } } testResults.close(); statement.close(); ReportData.enableOptimisations(conn, report, false); } catch (SQLException sqlex) { // log the cause but return a more user friendly message // logger.error("Requested change to report " + // report.getReportName() // + " would break view. Error = " + sqlex); // logger.error("SQL = " + report.getSQLForDetail()); throw new SQLException("The requested change would cause an error in the report: " + sqlex.getMessage() + ". SQL = " + statement, sqlex.getSQLState(), sqlex); } }
From source file:mom.trd.opentheso.bdd.helper.ConceptHelper.java
/** * Cette fonction permet d'ajouter un Concept la table Concept, en * paramtre un objet Classe Concept//from w ww. j a v a 2s . c o m * * @param ds * @param hierarchicalRelationship * @param idUser */ public void addAssociativeRelation(HikariDataSource ds, HierarchicalRelationship hierarchicalRelationship, int idUser) { // Role RT pour terme associs Connection conn; Statement stmt; try { // Get connection from pool conn = ds.getConnection(); try { conn.setAutoCommit(false); stmt = conn.createStatement(); try { if (!new RelationsHelper().addRelationHistorique(conn, hierarchicalRelationship.getIdConcept1(), hierarchicalRelationship.getIdThesaurus(), hierarchicalRelationship.getIdConcept2(), hierarchicalRelationship.getRole(), idUser, "ADD")) { conn.rollback(); conn.close(); return; } if (!new RelationsHelper().addRelationHistorique(conn, hierarchicalRelationship.getIdConcept2(), hierarchicalRelationship.getIdThesaurus(), hierarchicalRelationship.getIdConcept1(), hierarchicalRelationship.getRole(), idUser, "ADD")) { conn.rollback(); conn.close(); return; } String query = "Insert into hierarchical_relationship" + "(id_concept1, id_thesaurus, role, id_concept2)" + " values (" + "'" + hierarchicalRelationship.getIdConcept1() + "'" + ",'" + hierarchicalRelationship.getIdThesaurus() + "'" + ",'" + hierarchicalRelationship.getRole() + "'" + ",'" + hierarchicalRelationship.getIdConcept2() + "')"; stmt.executeUpdate(query); query = "Insert into hierarchical_relationship" + "(id_concept1, id_thesaurus, role, id_concept2)" + " values (" + "'" + hierarchicalRelationship.getIdConcept2() + "'" + ",'" + hierarchicalRelationship.getIdThesaurus() + "'" + ",'" + hierarchicalRelationship.getRole() + "'" + ",'" + hierarchicalRelationship.getIdConcept1() + "')"; stmt.executeUpdate(query); conn.commit(); } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception // if (!sqle.getMessage().contains("duplicate key value violates unique constraint")) { if (!sqle.getSQLState().equalsIgnoreCase("23505")) { log.error("Error while adding hierarchicalRelationship RT : " + hierarchicalRelationship.getIdConcept1(), sqle); } } }
From source file:org.apache.hadoop.hive.metastore.txn.TxnHandler.java
private boolean isDuplicateKeyError(SQLException ex) { switch (dbProduct) { case DERBY:// w ww . ja v a 2 s . c o m if ("23505".equals(ex.getSQLState())) { return true; } break; case MYSQL: //https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html if ((ex.getErrorCode() == 1022 || ex.getErrorCode() == 1062 || ex.getErrorCode() == 1586) && "23000".equals(ex.getSQLState())) { return true; } break; case SQLSERVER: //2627 is unique constaint violation incl PK, 2601 - unique key if (ex.getErrorCode() == 2627 && "23000".equals(ex.getSQLState())) { return true; } break; case ORACLE: if (ex.getErrorCode() == 1 && "23000".equals(ex.getSQLState())) { return true; } break; case POSTGRES: //http://www.postgresql.org/docs/8.1/static/errcodes-appendix.html if ("23505".equals(ex.getSQLState())) { return true; } break; default: throw new IllegalArgumentException("Unexpected DB type: " + dbProduct + "; " + getMessage(ex)); } return false; }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
/** * Updates the definition of a view within the DB. This method will not work * if the number of columns within the view are being changed. *//*from w w w.j a v a 2s . c o m*/ private boolean updateViewDbActionWithCreateOrReplace(Connection conn, BaseReportInfo report, boolean viewExists) throws SQLException, CantDoThatException, CodingErrorException, ObjectNotFoundException { String SQLCode = "CREATE OR REPLACE VIEW " + report.getInternalReportName() + " AS (" + report.getSQLForDetail() + ")"; boolean createOrReplaceWorked = true; Savepoint savepoint = null; PreparedStatement statement = null; try { savepoint = conn.setSavepoint("createOrReplaceSavepoint"); statement = conn.prepareStatement(SQLCode); statement.execute(); statement.close(); } catch (SQLException sqlex) { if (viewExists) { createOrReplaceWorked = false; conn.rollback(savepoint); } else { // if view didn't exist already, the error must be more serious // than just the CREATE OR REPLACE not working // logger.error("Requested change to report " + // report.getReportName() // + " would break view. Error = " + sqlex); // logger.error("SQL = " + report.getSQLForDetail()); throw new SQLException("The requested change would cause an error in the report: " + sqlex.getMessage() + ". SQL = " + statement, sqlex.getSQLState(), sqlex); } } return createOrReplaceWorked; }
From source file:com.funambol.foundation.items.dao.PIMContactDAO.java
/** * Gets the contact with given UID, provided it has the same userId as this * DAO. The contact photo will be provide if <code>withPhoto</code> is true, * otherwise the contact is retrived without photo * * @param uid corresponds to the id field in the fnbl_pim_contact table * @param withPhoto should the contact contain its photo ? * @throws DAOException/*from w w w . j a v a2s . c o m*/ * @return the contact as a ContactWrapper object. */ public ContactWrapper getItem(String uid, boolean withPhoto) throws DAOException { if (log.isTraceEnabled()) { log.trace("Retrieving contact '" + uid + "'"); } Connection con = null; PreparedStatement ps = null; ResultSet rs = null; ContactWrapper c; Long id = Long.parseLong(uid); try { // Looks up the data source when the first connection is created con = getUserDataSource().getRoutedConnection(userId); con.setReadOnly(true); ps = con.prepareStatement(SQL_GET_FNBL_PIM_CONTACT_BY_ID_USER); ps.setLong(1, id); ps.setString(2, userId); rs = ps.executeQuery(); c = createContact(uid, rs); DBTools.close(null, ps, rs); ps = con.prepareStatement(SQL_GET_FNBL_PIM_CONTACT_ITEM_BY_ID); ps.setLong(1, id); rs = ps.executeQuery(); try { addPIMContactItems(c, rs); } catch (SQLException sqle) { throw new SQLException( "Error while adding extra PIM contact " + "information. " + sqle.getMessage(), sqle.getSQLState()); } DBTools.close(null, ps, rs); ps = con.prepareStatement(SQL_GET_FNBL_PIM_ADDRESS_BY_ID); ps.setLong(1, id); rs = ps.executeQuery(); try { addPIMAddresses(c, rs); } catch (SQLException sqle) { throw new SQLException("Error while adding PIM address " + "information. " + sqle, sqle.getSQLState()); } if (withPhoto) { //if the photo type is null, there is nothing to do if (c.getPhotoType() != null) { if (ContactWrapper.PHOTO_IMAGE.equals(c.getPhotoType()) || ContactWrapper.PHOTO_URL.equals(c.getPhotoType())) { Photo photo = getPhoto(con, id); c.getContact().getPersonalDetail().setPhotoObject(photo); } else if (ContactWrapper.EMPTY_PHOTO.equals(c.getPhotoType())) { c.getContact().getPersonalDetail().setPhotoObject(new Photo(null, null, null)); } } } } catch (Exception e) { throw new DAOException("Error retrieving contact.", e); } finally { DBTools.close(con, ps, rs); } return c; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
private boolean createTable(Statement stmt, String cmd, String table) { boolean created = false; try {// www .j av a 2 s . co m stmt.execute(cmd); created = true; } catch (SQLException sqle) { if (SQL.DUPLICATE_TABLE.contains(sqle.getSQLState())) { log.log(Level.INFO, "{0}{1}{2}", new Object[] { "Table ", table, " already exists" }); created = true; } else { log.severe( "Could not create table: " + table + " " + sqle.getSQLState() + " " + sqle.getErrorCode()); sqle.printStackTrace(); } } return created; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
protected boolean dropTable(String table) { String cmd = "drop table " + getPTable(); PreparedStatement pstmt = null; boolean dropped = false; try {//from w ww . j a va 2 s. c o m Connection conn = this.getDefaultConn(); pstmt = conn.prepareStatement(cmd); pstmt.execute(); // conn.commit(); dropped = true; log.log(Level.FINE, "{0}{1}{2}", new Object[] { this, " dropped pause table ", table }); } catch (SQLException sqle) { if (!SQL.NONEXISTENT_TABLE.contains(sqle.getSQLState())) { log.severe(this + " could not drop table " + table + ":" + sqle.getSQLState() + ":" + sqle.getErrorCode()); sqle.printStackTrace(); } } return dropped; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
@SuppressWarnings("unused") private boolean clearTable(String table) { String cmd = "delete from " + getPTable() + " where true"; PreparedStatement pstmt = null; boolean dropped = false; try {/*from w w w .j av a2 s.co m*/ Connection conn = this.getDefaultConn(); pstmt = conn.prepareStatement(cmd); pstmt.execute(); // conn.commit(); dropped = true; log.log(Level.FINE, "{0}{1}{2}", new Object[] { this, " dropped pause table ", table }); } catch (SQLException sqle) { if (!SQL.NONEXISTENT_TABLE.contains(sqle.getSQLState())) { log.severe(this + " could not clear table " + table + ":" + sqle.getSQLState() + ":" + sqle.getErrorCode()); sqle.printStackTrace(); } } return dropped; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
@Deprecated private boolean log(String paxosID, int version, int slot, int ballotnum, int coordinator, PaxosPacketType type, String message) {//w w w.java 2 s.co m if (isClosed()) return false; if (!isLoggingEnabled()) return true; boolean logged = false; String cmd = "insert into " + getMTable() + " values (?, ?, ?, ?, ?, ?, ?)"; PreparedStatement localLogMsgStmt = null; Connection conn = null; try { conn = this.getDefaultConn(); localLogMsgStmt = conn.prepareStatement(cmd); // no re-use option localLogMsgStmt.setString(1, paxosID); localLogMsgStmt.setInt(2, version); localLogMsgStmt.setInt(3, slot); localLogMsgStmt.setInt(4, ballotnum); localLogMsgStmt.setInt(5, coordinator); localLogMsgStmt.setInt(6, type.getInt()); if (getLogMessageBlobOption()) { // localLogMsgStmt.setBlob(7, new StringReader(message)); Blob blob = conn.createBlob(); blob.setBytes(1, message.getBytes(CHARSET)); localLogMsgStmt.setBlob(7, blob); } else localLogMsgStmt.setString(7, message); int rowcount = localLogMsgStmt.executeUpdate(); assert (rowcount == 1); logged = true; log.log(Level.FINEST, "{0} inserted {1}, {2}, {3}, {4}, {5}", new Object[] { this, paxosID, slot, ballotnum, coordinator, message }); } catch (SQLException sqle) { if (SQL.DUPLICATE_KEY.contains(sqle.getSQLState())) { log.log(Level.FINE, "{0} log message {1} previously logged", new Object[] { this, message }); logged = true; } else { log.severe("SQLException while logging as " + cmd + " : " + sqle); sqle.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } finally { cleanup(localLogMsgStmt); cleanup(conn); } // no cleanup if statement is re-used return logged; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
private boolean connectDB() { boolean connected = false; int connAttempts = 0, maxAttempts = 1; long interAttemptDelay = 2000; // ms Properties props = new Properties(); // connection properties /* Providing a user name and PASSWORD is optional in embedded derby. * But, for some inscrutable, undocumented reason, it is important for * derby (or maybe c3p0) to have different user names for different * nodes, otherwise the performance with concurrent inserts and updates * is terrible. *//*from w ww .j a va 2 s . c om*/ props.put("user", SQL.getUser() + (isEmbeddedDB() ? this.getMyIDSanitized()/* this.myID */ : "")); props.put("password", SQL.getPassword()); ensureLogDirectoryExists(this.logDirectory); String dbCreation = SQL.getProtocolOrURL(SQL_TYPE) + (isEmbeddedDB() ? // embedded DB pre-creates DB to avoid c3p0 stack traces this.logDirectory + this.getMyDBName() + (!existsDB(SQL_TYPE, this.logDirectory, this.getMyDBName()) ? ";create=true" : "") : // else just use like a typical SQL DB this.getMyDBName() + "?createDatabaseIfNotExist=true"); try { dataSource = (ComboPooledDataSource) setupDataSourceC3P0(dbCreation, props); } catch (SQLException e) { log.severe("Could not create pooled data source to DB " + dbCreation); e.printStackTrace(); return false; } while (!connected && connAttempts < maxAttempts) { try { connAttempts++; log.info("Attempting getCursorConn() to db " + dbCreation); if (getCursorConn() == null) // test opening a connection this.cursorConn = dataSource.getConnection(); log.info("Connected to and created database " + this.getMyDBName()); connected = true; // mchange complains at unsuppressable INFO otherwise if (isEmbeddedDB()) fixURI(); // remove create flag } catch (SQLException sqle) { log.severe("Could not connect to derby DB: " + sqle.getSQLState() + ":" + sqle.getErrorCode()); sqle.printStackTrace(); try { Thread.sleep(interAttemptDelay); } catch (InterruptedException ie) { ie.printStackTrace(); } } finally { cleanupCursorConn(); } // close the test connection } return connected; }