List of usage examples for java.sql SQLException getSQLState
public String getSQLState()
SQLException
object. From source file:com.hangum.tadpole.rdb.core.editors.main.composite.MessageComposite.java
/** * SQLException to pretty message//from ww w. j a v a 2 s.co m * * @param sqlException * @param tadpoleMessageDAO * @return */ private String sqlExceptionToMsg(SQLException sqlException, TadpoleMessageDAO tadpoleMessageDAO) { String strNewMessage = ""; try { StringBuffer sbMsg = new StringBuffer(); sbMsg.append(String.format(Messages.get().MessageComposite_5, sqlException.getSQLState(), sqlException.getErrorCode())); sbMsg.append(String.format(Messages.get().MessageComposite_4, sqlException.getMessage())); strNewMessage = sbMsg.toString(); } catch (Exception e) { logger.error("SQLException to striing", e); //$NON-NLS-1$ strNewMessage = tadpoleMessageDAO.getStrMessage(); } return strNewMessage; }
From source file:io.confluent.connect.jdbc.EmbeddedDerby.java
public void close() throws SQLException { conn.close();/* w w w . j a v a 2 s. co m*/ // Derby requires more than just closing the connection to clear out the embedded data try { DriverManager.getConnection(getShutdownUrl()); } catch (SQLException se) { // Clean shutdown always throws this exception if (((se.getErrorCode() == 45000) && ("08006".equals(se.getSQLState())))) { // Note that for single database shutdown, the expected // SQL state is "08006", and the error code is 45000. } else { throw se; } } }
From source file:org.fcrepo.server.storage.ConnectionPool.java
private void shutdownEmbeddedDB(String username, String password) { logger.info("Shutting down embedded derby database."); try {// ww w . j ava 2s . com DriverManager.getConnection("jdbc:derby:;shutdown=true", username, password); } catch (SQLException e) { // Shutdown throws the XJ015 exception to confirm success. if (!e.getSQLState().equals("XJ015")) { logger.error("Embedded Derby DB did not shut down normally."); } } }
From source file:org.wso2.carbon.utils.dbcreator.DatabaseCreator.java
/** * executes given sql//w ww . jav a2 s . c o m * * @param sql * @throws Exception */ private void executeSQL(String sql) throws Exception { // Check and ignore empty statements if ("".equals(sql.trim())) { return; } ResultSet resultSet = null; try { if (log.isDebugEnabled()) { log.debug("SQL : " + sql); } boolean ret; int updateCount = 0, updateCountTotal = 0; ret = statement.execute(sql); updateCount = statement.getUpdateCount(); resultSet = statement.getResultSet(); do { if (!ret && updateCount != -1) { updateCountTotal += updateCount; } ret = statement.getMoreResults(); if (ret) { updateCount = statement.getUpdateCount(); resultSet = statement.getResultSet(); } } while (ret); if (log.isDebugEnabled()) { log.debug(sql + " : " + updateCountTotal + " rows affected"); } SQLWarning warning = conn.getWarnings(); while (warning != null) { log.debug(warning + " sql warning"); warning = warning.getNextWarning(); } conn.clearWarnings(); } catch (SQLException e) { if (e.getSQLState().equals("X0Y32") || e.getSQLState().equals("42710")) { // eliminating the table already exception for the derby and DB2 database types if (log.isDebugEnabled()) { log.info("Table Already Exists. Hence, skipping table creation"); } } else { throw new Exception("Error occurred while executing : " + sql, e); } } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { log.error("Error occurred while closing result set.", e); } } } }
From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseInitializer.java
/** * executes given sql/*from www .j av a 2 s .co m*/ * * @param sql Sql query to be executed * @throws DashboardPortalException */ private void executeSQL(String sql) throws DashboardPortalException { // Check and ignore empty statements if ("".equals(sql.trim())) { return; } ResultSet resultSet = null; Connection conn = null; try { if (log.isDebugEnabled()) { log.debug("SQL : " + sql); } boolean ret; int updateCount, updateCountTotal = 0; ret = statement.execute(sql); updateCount = statement.getUpdateCount(); resultSet = statement.getResultSet(); do { if (!ret) { if (updateCount != -1) { updateCountTotal += updateCount; } } ret = statement.getMoreResults(); if (ret) { updateCount = statement.getUpdateCount(); resultSet = statement.getResultSet(); } } while (ret); if (log.isDebugEnabled()) { log.debug(sql + " : " + updateCountTotal + " rows affected"); } conn = dataSource.getConnection(); SQLWarning warning = conn.getWarnings(); while (warning != null) { if (log.isDebugEnabled()) { log.debug(warning + " sql warning"); warning = warning.getNextWarning(); } } conn.clearWarnings(); } catch (SQLException e) { if (e.getSQLState().equals("X0Y32") || e.getSQLState().equals("42710")) { // eliminating the table already exception for the derby and DB2 database types if (log.isDebugEnabled()) { log.info("Table Already Exists. Hence, skipping table creation"); } } else { throw new DashboardPortalException("Error occurred while executing : " + sql, e); } } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { log.error("Error occurred while closing result set.", e); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { log.error("Error occurred while closing sql connection.", e); } } } }
From source file:com.yahoo.dba.perf.myperf.springmvc.VardiffController.java
@Override protected ModelAndView handleRequestImpl(HttpServletRequest req, HttpServletResponse resp) throws Exception { int status = Constants.STATUS_OK; String message = "OK"; logger.info("receive url " + req.getQueryString()); QueryParameters qps = null;/*w ww . j ava 2 s. com*/ DBInstanceInfo dbinfo = null; DBInstanceInfo dbinfo2 = null; DBConnectionWrapper connWrapper = null; DBConnectionWrapper connWrapper2 = null; qps = WebAppUtil.parseRequestParameter(req); qps.setSql("mysql_global_variables"); qps.getSqlParams().put("p_1", ""); String group2 = req.getParameter("p_1"); String host2 = req.getParameter("p_2"); //validation input String validation = qps.validate(); if (validation == null || validation.isEmpty()) { //do we have such query? try { QueryInputValidator.validateSql(this.frameworkContext.getSqlManager(), qps); } catch (Exception ex) { validation = ex.getMessage(); } } if (validation != null && !validation.isEmpty()) return this.respondFailure(validation, req); dbinfo = this.frameworkContext.getDbInfoManager().findDB(qps.getGroup(), qps.getHost()); if (dbinfo == null) return this.respondFailure("Cannot find record for DB (" + qps.getGroup() + ", " + qps.getHost() + ")", req); dbinfo2 = this.frameworkContext.getDbInfoManager().findDB(group2, host2); if (dbinfo2 == null) return this.respondFailure("Cannot find record for DB (" + group2 + ", " + host2 + ")", req); try { connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo); if (connWrapper == null) { status = Constants.STATUS_BAD; message = "failed to connect to target db (" + dbinfo + ")"; } else { connWrapper2 = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo2); if (connWrapper2 == null) { status = Constants.STATUS_BAD; message = "failed to connect to target db (" + dbinfo2 + ")"; } } } catch (Throwable th) { logger.log(Level.SEVERE, "Exception", th); status = Constants.STATUS_BAD; message = "Failed to get connection to target db (" + dbinfo + "): " + th.getMessage(); } if (status == -1) return this.respondFailure(message, req); //when we reach here, at least we have valid query and can connect to db WebAppUtil.storeLastDbInfoRequest(qps.getGroup(), qps.getHost(), req); ModelAndView mv = null; ResultList rList = null; ResultList rList2 = null; try { rList = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper, qps.getMaxRows()); rList2 = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper2, qps.getMaxRows()); logger.info("Done query " + qps.getSql() + " with " + (rList != null ? rList.getRows().size() : 0) + " records, " + (rList2 != null ? rList2.getRows().size() : 0) + " records"); WebAppUtil.closeDBConnection(req, connWrapper, false); WebAppUtil.closeDBConnection(req, connWrapper2, false); } catch (Throwable ex) { logger.log(Level.SEVERE, "Exception", ex); if (ex instanceof SQLException) { SQLException sqlEx = SQLException.class.cast(ex); String msg = ex.getMessage(); logger.info(sqlEx.getSQLState() + ", " + sqlEx.getErrorCode() + ", " + msg); //check if the connection is still good if (!DBUtils.checkConnection(connWrapper.getConnection())) { WebAppUtil.closeDBConnection(req, connWrapper, true); } else WebAppUtil.closeDBConnection(req, connWrapper, true); if (!DBUtils.checkConnection(connWrapper2.getConnection())) { WebAppUtil.closeDBConnection(req, connWrapper2, true); } else WebAppUtil.closeDBConnection(req, connWrapper2, true); } else { WebAppUtil.closeDBConnection(req, connWrapper, false); WebAppUtil.closeDBConnection(req, connWrapper2, false); } status = Constants.STATUS_BAD; message = "Exception: " + ex.getMessage(); } if (status == Constants.STATUS_BAD) return this.respondFailure(message, req); HashMap<String, String> param1 = new HashMap<String, String>(rList.getRows().size()); HashMap<String, String> param2 = new HashMap<String, String>(rList2.getRows().size()); for (ResultRow r : rList.getRows()) { param1.put(r.getColumns().get(0), r.getColumns().get(1)); } for (ResultRow r : rList2.getRows()) { param2.put(r.getColumns().get(0), r.getColumns().get(1)); } ColumnDescriptor desc = new ColumnDescriptor(); desc.addColumn("VARIABLE_NAME", false, 1); desc.addColumn("DB1", false, 2); desc.addColumn("DB2", false, 3); ResultList fList = new ResultList(); fList.setColumnDescriptor(desc); HashSet<String> diffSet = new HashSet<String>(); for (Map.Entry<String, String> e : param1.entrySet()) { String k = e.getKey(); String v = e.getValue(); if (v != null) v = v.trim(); else v = ""; String v2 = null; if (param2.containsKey(k)) v2 = param2.get(k); if (v2 != null) v2 = v2.trim(); else v2 = ""; if (!v.equals(v2)) { ResultRow row = new ResultRow(); List<String> cols = new ArrayList<String>(); cols.add(k); cols.add(v); cols.add(v2); row.setColumns(cols); row.setColumnDescriptor(desc); fList.addRow(row); diffSet.add(k); } } for (Map.Entry<String, String> e : param2.entrySet()) { String k = e.getKey(); String v = e.getValue(); if (v == null || v.isEmpty()) continue; if (diffSet.contains(k) || param1.containsKey(k)) continue; ResultRow row = new ResultRow(); List<String> cols = new ArrayList<String>(); cols.add(k); cols.add(""); cols.add(v); row.setColumns(cols); row.setColumnDescriptor(desc); fList.addRow(row); } mv = new ModelAndView(this.jsonView); if (req.getParameter("callback") != null && req.getParameter("callback").trim().length() > 0) mv.addObject("callback", req.getParameter("callback"));//YUI datasource binding mv.addObject("json_result", ResultListUtil.toJSONString(fList, qps, status, message)); return mv; }
From source file:org.apache.hadoop.chukwa.database.TestDatabaseWebJson.java
protected void verifyTableData(String table) { Calendar startCalendar = new GregorianCalendar(); // startCalendar.add(Calendar.HOUR_OF_DAY,-1); startCalendar.add(Calendar.MINUTE, -30); long startTime = startCalendar.getTime().getTime(); Calendar endCalendar = new GregorianCalendar(); // endCalendar.add(Calendar.HOUR_OF_DAY,1); long endTime = endCalendar.getTime().getTime(); String url = data_url + "?table=" + table + "&start=" + startTime + "&end=" + endTime; System.out.println(url);/*from w ww . j a v a2s.co m*/ HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); try { /* * 1. get the json result for the specified table */ int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.out.println("Http Error: " + method.getStatusLine()); } BufferedReader reader = new BufferedReader( new InputStreamReader(method.getResponseBodyAsStream(), method.getResponseCharSet())); String json_str = ""; String str; while ((str = reader.readLine()) != null) { json_str += str; } /* * 2. convert the json string to individual field and compare it * with the database */ String cluster = "demo"; DatabaseWriter db = new DatabaseWriter(cluster); JSONArray json_array = new JSONArray(json_str); for (int i = 0; i < json_array.length(); i++) { JSONObject row_obj = json_array.getJSONObject(i); // get the database row String queryString = getDatabaseQuery(table, row_obj); Macro m = new Macro(startTime, endTime, queryString); ResultSet rs = db.query(m.toString()); // move to the first record rs.next(); ResultSetMetaData md = rs.getMetaData(); Iterator names = row_obj.keys(); while (names.hasNext()) { String name = (String) names.next(); String jsonValue = (String) row_obj.get(name); String dbValue = rs.getString(name); int dbCol = rs.findColumn(name); int dbType = md.getColumnType(dbCol); if (dbType == 93) { // timestamp dbValue = Long.toString(rs.getTimestamp(name).getTime()); } // System.out.println("compare "+name+":"+dbType+":"+dbValue+":"+jsonValue); assertEquals(dbValue, jsonValue); } } db.close(); } catch (SQLException e) { System.out.println("Exception: " + e.toString() + ":" + e.getMessage()); System.out.println("Exception: " + e.toString() + ":" + e.getSQLState()); System.out.println("Exception: " + e.toString() + ":" + e.getErrorCode()); fail("SQL Error:" + ExceptionUtil.getStackTrace(e)); } catch (Exception eOther) { System.out.println("Other Exception: " + eOther.toString()); eOther.printStackTrace(); fail("Error:" + ExceptionUtil.getStackTrace(eOther)); } finally { } }
From source file:com.ipcglobal.fredimportcdh.TsvsToImpala.java
/** * Process tables./*from ww w . j ava 2s . c om*/ * * @throws Exception the exception */ private void processTables() throws Exception { String jdbcImpalaDriverClass = this.properties.getProperty("jdbcImpalaDriverClass").trim(); String jdbcImpalaUrl = this.properties.getProperty("jdbcImpalaUrl").trim(); String jdbcImpalaLogin = this.properties.getProperty("jdbcImpalaLogin").trim(); String jdbcImpalaPassword = this.properties.getProperty("jdbcImpalaPassword").trim(); String databaseNameFred = this.properties.getProperty("databaseNameFred").trim(); String tableNameFred = properties.getProperty("tableNameFred"); String stageTableSuffix = "_staging"; Connection con = null; Statement statement = null; String databaseTableName = databaseNameFred + "." + tableNameFred; String databaseStageTableName = databaseNameFred + "." + tableNameFred + stageTableSuffix; try { Class.forName(jdbcImpalaDriverClass); con = DriverManager.getConnection(jdbcImpalaUrl, jdbcImpalaLogin, jdbcImpalaPassword); statement = con.createStatement(); log.info("\tDrop/create internal and external staging table"); statement.executeUpdate("DROP TABLE IF EXISTS " + databaseTableName); statement.executeUpdate("DROP TABLE IF EXISTS " + databaseStageTableName); log.info("\tCreate external staging table against the tsv's in HDFS"); statement.executeUpdate(createStageTableStatement(databaseStageTableName)); statement.executeUpdate("REFRESH " + databaseStageTableName); log.info("\tCreate internal table as select from external staging table"); String sqlCreateAs = "create table " + databaseTableName + " stored as parquet as select * from " + databaseStageTableName; statement.executeUpdate(sqlCreateAs); statement.executeUpdate("REFRESH " + databaseTableName); log.info("\tDrop the staging table"); statement.executeUpdate("DROP TABLE IF EXISTS " + databaseStageTableName); log.info("\tStart - COMPUTE STATS on internal table"); String sqlComputeStats = "COMPUTE STATS " + databaseTableName; try { long before = System.currentTimeMillis(); log.info(sqlComputeStats); statement.executeUpdate(sqlComputeStats); log.info("\tCOMPUTE STATS Insert Ok, Elapsed=" + convertMSecsToHMmSs(System.currentTimeMillis() - before)); } catch (Exception e) { log.error("COMPUTE STATS, statement=" + sqlComputeStats, e); throw e; } } catch (SQLException se) { log.error(se); log.error("Cause: " + se.getCause()); log.error("getErrorCode: " + se.getErrorCode()); log.error("getSQLState: " + se.getSQLState()); se.printStackTrace(); throw se; } catch (Exception e) { log.error(e); e.printStackTrace(); throw e; } finally { try { if (statement != null) statement.close(); } catch (Exception e) { } try { if (con != null) con.close(); } catch (Exception e) { } } }
From source file:com.splicemachine.derby.test.TPCHIT.java
@Test public void sql8InvalidMergeJoin() throws Exception { try {/*from ww w. j ava 2 s . co m*/ executeQuery(getContent("8-invalid-merge.sql"), "", true); } catch (SQLException e) { // Error expected due to invalid MERGE join: // ERROR 42Y69: No valid execution plan was found for this statement. assertEquals("42Y69", e.getSQLState()); } }
From source file:com.norconex.collector.core.data.store.impl.jdbc.JDBCCrawlDataStore.java
@Override public void close() { if (database == Database.DERBY) { Connection conn = null;/*www . j a v a 2 s. c o m*/ try { LOG.info("Closing Derby database..."); conn = new EmbeddedDriver().connect("jdbc:derby:" + dbDir + ";shutdown=true", null); } catch (SQLException e) { if (!DERBY_STATE_SHUTDOWN_SUCCESS.equals(e.getSQLState())) { throw new CrawlDataStoreException("Cannot shutdown Derby database.", e); } LOG.info("Derby database closed."); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { LOG.info("Problem closing database " + "shutdown connection.", e); } } } } }