Example usage for java.sql SQLException SQLException

List of usage examples for java.sql SQLException SQLException

Introduction

In this page you can find the example usage for java.sql SQLException SQLException.

Prototype

public SQLException(Throwable cause) 

Source Link

Document

Constructs a SQLException object with a given cause.

Usage

From source file:com.globalsight.ling.tm3.core.TuStorage.java

/**
 * Delete TUVs, along with their history.
 * /*from w  w  w . j  a v a2  s  .  c o m*/
 * @param conn
 * @param tuv
 * @throws IllegalArgumentException
 *             if you try to delete the source TUV for a TU.
 */
public void deleteTuvs(Connection conn, List<TM3Tuv<T>> tuvs) throws SQLException {
    if (tuvs.size() == 0) {
        return;
    }
    try {
        StatementBuilder sb = new StatementBuilder("DELETE FROM ").append(storage.getTuvExtTableName())
                .append(" WHERE tuvId IN (?").addValue(tuvs.get(0).getId());
        for (int i = 1; i < tuvs.size(); i++) {
            sb.append(",?").addValue(tuvs.get(i).getId());
        }
        sb.append(")");
        SQLUtil.exec(conn, sb);

        // Events will cascade
        sb = new StatementBuilder("DELETE FROM ").append(storage.getTuvTableName()).append(" WHERE id IN (?")
                .addValue(tuvs.get(0).getId());
        for (int i = 1; i < tuvs.size(); i++) {
            sb.append(",?").addValue(tuvs.get(i).getId());
        }
        sb.append(")");
        SQLUtil.exec(conn, sb);
    } catch (Exception e) {
        throw new SQLException(e);
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.common.virtualdatasourcequery.teiid.impl.HiveTeiidConnectorImpl.java

public Connection createConnection() throws SQLException {
    try {/*  w w w .  j  a  v  a2  s  . co m*/
        if ((connection == null) || connection.isClosed()) {
            // HIVE DRIVER DOESN'T SUPPORT XAConnection, PooledDataSource
            // JNDI connection is still recommended by HIVE Connection
            Class.forName(driver);
            connection = DriverManager.getConnection(jdbcURL, userName, password);
            if ((databaseName != null) && !databaseName.toLowerCase().equals("default")) {
                Statement statement = connection.createStatement();
                log.debug("HIVE USE NON-DEFAULT DATABASE:  EXECUTE UPDATE - [USE " + databaseName + "]");
                statement.executeUpdate("USE " + databaseName);
                statement.close();
            }
        }
        return connection;
    } catch (SQLException sqlEx) {
        throw sqlEx;
    } catch (Exception ex) {
        throw new SQLException(ex);
    }
}

From source file:com.taobao.adfs.database.tdhsocket.client.util.ConvertUtil.java

public static Long getTimeFromString(String stringVal, @Nullable Calendar cal) throws SQLException {
    if (stringVal == null) {
        return null;
    }//from ww w  .ja  v a 2 s. c o  m
    String val = stringVal.trim();
    if (val.length() == 0) {
        return null;
    }
    if (val.equals("0") || val.equals("0000-00-00") || val.equals("0000-00-00 00:00:00")
            || val.equals("00000000000000") || val.equals("0")) {
        Calendar calendar = null;
        if (cal != null) {
            calendar = Calendar.getInstance(cal.getTimeZone());
        } else {
            calendar = Calendar.getInstance();
        }
        calendar.set(Calendar.YEAR, 1);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTimeInMillis();
    }

    DateFormat dateFormat = DateFormat.getDateTimeInstance();
    if (cal != null) {
        TimeZone timeZone = cal.getTimeZone();
        dateFormat.setTimeZone(timeZone);
    }
    try {
        return dateFormat.parse(val).getTime();
    } catch (ParseException e) {
        throw new SQLException("Parse date failure:" + val);
    }
}

From source file:com.iksgmbh.sql.pojomemodb.sqlparser.CreateTableParser.java

private String createUniqueConstraint(String unparsedRest, TableMetaData tableMetaData) throws SQLException {
    String toReturn = unparsedRest.substring(CONSTRAINT.length()).trim();
    InterimParseResult parseResult = parseNextValue(toReturn, SPACE + UNIQUE);

    if (StringUtils.isEmpty(parseResult.delimiter)) {
        throw new SQLException("Cannot parse to Primary Key Constraint: " + unparsedRest
                + " Expected something like 'CONSTRAINT UNIQUE_ID UNIQUE (COLUMN_NAME)'.");
    }/*from   ww w  .  j a v  a2  s . com*/

    String uniqueConstraintId = removeSurroundingQuotes(parseResult.parsedValue);
    parseResult = parseNextValue(parseResult.unparsedRest, CLOSING_PARENTHESIS);
    String constraintColumnName = null;

    if (parseResult.unparsedRest == null) {
        toReturn = "";
        constraintColumnName = parseResult.parsedValue + CLOSING_PARENTHESIS;
    } else {
        toReturn = parseResult.unparsedRest.trim();
        constraintColumnName = parseResult.parsedValue + CLOSING_PARENTHESIS;

        int pos = constraintColumnName.toUpperCase().indexOf(USING_INDEX.toUpperCase());
        if (pos > 0) {
            constraintColumnName = constraintColumnName.substring(0, pos).trim();
        }
    }

    if (constraintColumnName.startsWith(OPENING_PARENTHESIS)) {
        if (constraintColumnName.endsWith(CLOSING_PARENTHESIS)) {
            constraintColumnName = constraintColumnName.substring(1, constraintColumnName.length() - 1);
        } else {
            throw new SQLException("Cannot parse to primary key constraint: " + unparsedRest
                    + ". Expected something like 'CONSTRAINT UNIQUE_ID UNIQUE KEY (COLUMN_NAME)'.");
        }
    } else {
        if (constraintColumnName.endsWith(CLOSING_PARENTHESIS)) {
            throw new SQLException("Cannot parse to primary key constraint: " + unparsedRest
                    + ". Expected something like 'CONSTRAINT UNIQUE UNIQUE (COLUMN_NAME)'.");
        }
    }

    constraintColumnName = removeSurroundingQuotes(constraintColumnName);
    Column column = ((Table) tableMetaData).getColumn(constraintColumnName);
    column.setUniqueConstraintId(uniqueConstraintId);

    if (toReturn.startsWith(COMMA))
        toReturn = toReturn.substring(1);

    return toReturn.trim();
}

From source file:com.softberries.klerk.dao.DocumentDao.java

@Override
public void create(Document d) throws SQLException {
    try {//from www.  jav  a 2  s  . c o m
        init();
        st = conn.prepareStatement(SQL_INSERT_DOCUMENT, Statement.RETURN_GENERATED_KEYS);
        st.setString(1, d.getTitle());
        st.setString(2, d.getNotes());
        st.setDate(3, new java.sql.Date(d.getCreatedDate().getTime()));
        st.setDate(4, new java.sql.Date(d.getTransactionDate().getTime()));
        st.setDate(5, new java.sql.Date(d.getDueDate().getTime()));
        st.setString(6, d.getPlaceCreated());
        st.setInt(7, d.getDocumentType());
        st.setLong(8, d.getCreator().getId());
        st.setLong(9, d.getBuyer().getId());
        st.setLong(10, d.getSeller().getId());
        // run the query
        int i = st.executeUpdate();
        System.out.println("i: " + i);
        if (i == -1) {
            System.out.println("db error : " + SQL_INSERT_DOCUMENT);
        }
        generatedKeys = st.getGeneratedKeys();
        if (generatedKeys.next()) {
            d.setId(generatedKeys.getLong(1));
        } else {
            throw new SQLException("Creating document failed, no generated key obtained.");
        }
        //if the document creation was successful, add document items
        DocumentItemDao idao = new DocumentItemDao(this.filePath);
        for (DocumentItem di : d.getItems()) {
            di.setDocument_id(d.getId());
            idao.create(di, run, conn, generatedKeys);
        }
        conn.commit();
    } catch (Exception e) {
        //rollback the transaction but rethrow the exception to the caller
        conn.rollback();
        e.printStackTrace();
        throw new SQLException(e);
    } finally {
        close(conn, st, generatedKeys);
    }
}

From source file:net.mlw.vlh.adapter.jdbc.dynabean.fix.JDBCDynaClass.java

/**
 * <p>Loads and returns the <code>Class</code> of the given name.
 * By default, a load from the thread context class loader is attempted.
 * If there is no such class loader, the class loader used to load this
 * class will be utilized.</p>//from   w  ww  .j a  v  a  2s.  co  m
 *
 * @exception SQLException if an exception was thrown trying to load
 *  the specified class
 */
protected Class loadClass(String className) throws SQLException {

    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null) {
            cl = this.getClass().getClassLoader();
        }
        return (cl.loadClass(className));
    } catch (Exception e) {
        throw new SQLException("Cannot load column class '" + className + "': " + e);
    }

}

From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java

/**
 * Helper function gets the rows from the foreign CouchDB server and returns
 * them as a JSONArray./*from   w ww. j ava2 s. co  m*/
 */
private static InputStreamReader getViewStream(String user, String pw, String url, String view, String limit,
        boolean reduce, String groupLevel, boolean hasReducer) throws SQLException {
    String full_url = "";
    try {
        // TODO: stringbuffer this for efficiency
        full_url = makeUrl(url, view);
        String sep = (view.indexOf("?") == -1) ? "?" : "&";
        if (limit != null && limit.length() > 0) {
            full_url += sep + "limit=" + limit;
            sep = "&";
        }

        // These options only apply if a reducer function is present.
        if (hasReducer) {
            if (!reduce) {
                full_url += sep + "reduce=false";
                if (sep.equals("?"))
                    sep = "&";
            }
            if (groupLevel.toUpperCase().equals("EXACT"))
                full_url += sep + "group=true";
            else if (groupLevel.toUpperCase().equals("NONE"))
                full_url += sep + "group=false";
            else
                full_url += sep + "group_level=" + groupLevel;
        }

        logger.log(Level.FINE, "Attempting CouchDB request with URL: " + full_url);

        URL u = new URL(full_url);
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();
        if (user != null && user.length() > 0) {
            uc.setRequestProperty("Authorization", "Basic " + buildAuthHeader(user, pw));
        }
        uc.connect();
        return new InputStreamReader(uc.getInputStream());

    } catch (MalformedURLException e) {
        throw new SQLException("Bad URL: " + full_url);
    } catch (IOException e) {
        if (hasReducer) { // try again but without the reduce args..
            try {
                return getViewStream(user, pw, url, view, limit, reduce, groupLevel, false);
            } catch (SQLException e2) { // No good.

            }
        }
        throw new SQLException("Could not read data from URL: " + full_url);
    }
}

From source file:com.cws.esolutions.security.dao.reference.impl.SecurityReferenceDAOImpl.java

/**
 * @see com.cws.esolutions.security.dao.reference.interfaces.ISecurityReferenceDAO#listAvailableServices()
 *///from  w w w.j  ava  2 s  .com
public synchronized Map<String, String> listAvailableServices() throws SQLException {
    final String methodName = ISecurityReferenceDAO.CNAME + "#listAvailableServices() throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    Map<String, String> serviceMap = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL retrAvailableServices()}");

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (DEBUG) {
                DEBUGGER.debug("ResultSet: {}", resultSet);
            }

            if (resultSet.next()) {
                resultSet.beforeFirst();
                serviceMap = new HashMap<String, String>();

                while (resultSet.next()) {
                    serviceMap.put(resultSet.getString(1), resultSet.getString(2));
                }

                if (DEBUG) {
                    DEBUGGER.debug("Map<String, String>: {}", serviceMap);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return serviceMap;
}

From source file:com.adaptris.jdbc.connection.FailoverDataSource.java

/**
 * @see java.sql.Wrapper#unwrap(java.lang.Class)
 *///w w w . ja va2 s. co  m
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
    throw new SQLException("Nothing to unwrap");
}

From source file:org.neo4j.jdbc.http.HttpResultSet.java

@Override
@SuppressWarnings("rawtypes")
public Array getArray(int columnIndex) throws SQLException {

    checkClosed();//  ww  w. j  av  a 2  s  .com
    // Default list for null array
    List result = new ArrayList<String>();
    Object obj = get(columnIndex);
    if (obj != null) {
        if (!obj.getClass().isArray()) {
            throw new SQLException("Column " + columnIndex + " is not an Array");
        }

        result = Arrays.asList((Array) obj);
    }
    return new ListArray(result, Array.getObjectType(result.get(0)));
}