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.l2jfree.sql.L2DataSource.java

/**
 * Obtains <TT>CURRENT_DATABASE</TT> and <TT>CURRENT_SCHEMA</TT> on an arbitrary DBMS.
 * /*from   ww w  . j  a va  2 s.  c om*/
 * @throws SQLException if a SQL error occurs
 */
public final void initSQLContext() throws SQLException {
    Connection con = null;

    // remove leftover tables
    try {
        con = getConnection();

        DatabaseMetaData dmd = con.getMetaData();

        final List<String> tables = new ArrayList<String>();
        {
            final ResultSet rs = dmd.getTables(null, null, "_zzz%", BASE_TABLE);
            while (rs.next())
                tables.add(rs.getString(3));
            rs.close();
        }

        int removed = 0;
        final Statement s = con.createStatement();
        for (String table : tables) {
            try {
                s.executeUpdate("DROP TABLE " + table);
                removed++;
            } catch (SQLException e) {
                // table is owned by another user
            }
        }
        s.close();

        if (removed > 0)
            _log.info("Removed " + removed + " temporary tables.");
    } finally {
        L2Database.close(con);
    }

    try {
        con = getConnection();

        // generate a random table name
        final String table = "_zzz" + Rnd.getString(5, Rnd.LOWER_CASE_LETTERS);
        // DO NOT LOOK IT UP NOW

        // attempt to create in current schema instead
        {
            final Statement s = con.createStatement();
            s.executeUpdate("CREATE TABLE " + table + " (x INT)");
            s.close();
        }

        // table did not exist in current schema, we can look it up now
        {
            DatabaseMetaData dmd = con.getMetaData();

            final ResultSet rs = dmd.getTables(null, null, table, BASE_TABLE);
            if (rs.next()) {
                _database = rs.getString(1);
                _schema = rs.getString(2);
            } else
                throw new SQLException("Anomaly/Malfunction."); // should never happen

            if (rs.next())
                throw new SQLException("Please try again later."); // should never happen

            rs.close();
        }

        // remove table
        {
            final Statement s = con.createStatement();
            s.executeUpdate("DROP TABLE " + table);
            s.close();
        }
    } finally {
        L2Database.close(con);
    }
}

From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java

/**
 * Checks for the existence of the base table and optionally creates it if
 * it doesn't exist// ww  w  .j  a  v a 2 s .co m
 *
 * @param c Database connection to use
 * @param baseTable Base Table Definition (Table or View)
 * @param autoCreate Whether to auto create the table or view
 * @return Whether the table or view exists
 * @throws SQLException Exception if it exists in an invalid format
 */
protected boolean checkBaseTable(Connection c, BaseTableDef baseTable) throws SQLException {
    String schema = baseTable.getNameDef().getSchema();
    String name = baseTable.getNameDef().getName().toUpperCase();

    // VALIDATE TABLE OR VIEW
    ResultSet rs = c.getMetaData().getTables(null, schema, name, null);
    try {
        boolean found = false;
        while (rs.next()) {
            if (name.equalsIgnoreCase(rs.getString(3))) {
                found = true;
                break;
            }
        }

        if (!found) {
            // throw new TableDoesNotExistException( "Table or View [" +
            // baseTable.getNameDef() + "] does not exist" );
            return false;
        }
    } finally {
        rs.close();
    }

    // VALIDATE THE COLUMNS
    for (ColumnDef col : baseTable.getColumns()) {
        rs = c.getMetaData().getColumns(null, schema, name, col.getName().toUpperCase());
        try {
            boolean found = false;
            while (rs.next()) {
                if (col.getName().equalsIgnoreCase(rs.getString(4))) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                throw new SQLException("Table or View [" + baseTable.getNameDef() + "] does not have a Column ["
                        + col.getName() + "]");
            }
        } finally {
            rs.close();
        }
    }

    return true;
}

From source file:com.taobao.tdhs.client.util.ConvertUtil.java

public static Long getTimeFromString(String stringVal, @Nullable Calendar cal) throws SQLException {
    if (stringVal == null) {
        return null;
    }/*from   w w w. j a  v a2 s . c  om*/
    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;
    if (val.length() == "yyyy-MM-dd".length()) {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    } else {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }
    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:hermes.store.schema.DefaultJDBCAdapter.java

public void remove(Connection connection, String storeId, Message message) throws SQLException, JMSException {
    final QueryRunner runner = new QueryRunner();

    if (runner.update(connection, "delete from stores where storeid=? and messageid=?",
            new Object[] { storeId, message.getJMSMessageID() }) > 0) {
        runner.update(connection, "delete from messages where messageid=?",
                new Object[] { message.getJMSMessageID() });
    } else {//from   w ww.j  av  a  2s .  c  om
        throw new SQLException("No message id=" + message.getJMSMessageID() + " exists in store=" + storeId);
    }
}

From source file:org.neo4j.jdbc.http.driver.CypherExecutor.java

/**
 * Rollback the current transaction./* w  ww  .  j  a  v a  2  s. c o m*/
 *
 * @throws SQLException if there is no transaction to rollback
 */
public void rollback() throws SQLException {
    if (this.getOpenTransactionId() > 0) {
        // Prepare the request
        HttpDelete request = new HttpDelete(currentTransactionUrl);
        Neo4jResponse response = this.executeHttpRequest(request);
        if (response.code != 200 & response.hasErrors()) {
            throw new SQLException(response.displayErrors());
        }
        this.currentTransactionUrl = this.transactionUrl;
    }
}

From source file:com.zotoh.core.db.JDBCPool.java

private JConnection next() throws SQLException {
    try {//from w w  w  . j  av a  2s .  com
        return new JConnection(this, (PoolableConnection) _pool.borrowObject());
    } catch (SQLException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLException("No free connection");
    }

}

From source file:gr.osmosis.rcpsamples.contact.db.derby.DerbyContactsDAO.java

public boolean createContact(Contact contact) {
    if (contact == null) {
        throw new NullPointerException("contact parameter");
    }//  www .  j  av a2s. com

    int rows = 0;

    try {
        StringBuffer sbInsert = new StringBuffer();

        sbInsert.append("INSERT INTO ");
        sbInsert.append(ContactsConstants.CONTACTS_TABLE_NAME);
        sbInsert.append("(");
        sbInsert.append(ContactsConstants.CONTACTS_COL_FNAME + ", ");
        sbInsert.append(ContactsConstants.CONTACTS_COL_LNAME + ", ");
        sbInsert.append(ContactsConstants.CONTACTS_COL_PHONE + ", ");
        sbInsert.append(ContactsConstants.CONTACTS_COL_ADDRESS + ", ");
        sbInsert.append(ContactsConstants.CONTACTS_COL_CITY + ", ");
        sbInsert.append(ContactsConstants.CONTACTS_COL_ZIP);
        sbInsert.append(")");
        sbInsert.append(" VALUES (");
        sbInsert.append(" '" + contact.getFname() + "' , ");
        sbInsert.append(" '" + contact.getLname() + "' , ");
        sbInsert.append(" '" + contact.getPhone() + "' , ");
        sbInsert.append(" '" + contact.getAddress() + "' , ");
        sbInsert.append(" '" + contact.getCity() + "' , ");
        sbInsert.append(" '" + contact.getZip() + "'  ");
        sbInsert.append(")");

        DataSource d = DerbyDAOFactory.getDataSource();
        QueryRunner run = new QueryRunner(d);

        rows = run.update(sbInsert.toString());

        if (rows != 1) {
            throw new SQLException("executeUpdate return value: " + rows);
        }

    } catch (SQLException ex) {
        ex.printStackTrace();
        return false;
    }

    return true;

}

From source file:net.tirasa.connid.bundles.soap.wssample.ProvisioningImpl.java

@Override
public List<WSUser> query(Operand query) {
    LOG.debug("Query request received");

    List<WSUser> results = new ArrayList<WSUser>();

    Connection conn = null;/*from   ww  w  .  j a  va 2s .  c om*/
    try {

        String queryString = "SELECT * FROM user" + (query == null ? "" : " WHERE " + query.toString());

        queryString = queryString.replaceAll("__NAME__", "userId").replaceAll("__UID__", "userId")
                .replaceAll("__PASSWORD__", "password");

        LOG.debug("Execute query: {}", queryString);

        if (queryString == null || queryString.length() == 0) {
            throw new SQLException("Invalid query [" + queryString + "]");
        }

        conn = connect();
        Statement statement = conn.createStatement();

        ResultSet rs = statement.executeQuery(queryString);

        ResultSetMetaData metaData = rs.getMetaData();
        LOG.debug("Metadata: {}", metaData);

        while (rs.next()) {
            WSUser user = new WSUser();

            for (int i = 0; i < metaData.getColumnCount(); i++) {
                WSAttributeValue attr = new WSAttributeValue();
                attr.setName(metaData.getColumnLabel(i + 1));
                if (StringUtils.isNotBlank(rs.getString(i + 1))) {
                    attr.addValue(rs.getString(i + 1));
                }
                if ("userId".equalsIgnoreCase(metaData.getColumnName(i + 1))) {
                    attr.setKey(true);
                    user.setAccountid(rs.getString(i + 1));
                }

                user.addAttribute(attr);
            }

            results.add(user);
        }

        LOG.debug("Retrieved users: {}", results);
    } catch (SQLException e) {
        LOG.error("Search operation failed", e);
    } finally {
        if (conn != null) {
            try {
                close(conn);
            } catch (SQLException ignore) {
                // ignore exception
            }
        }
    }

    return results;
}

From source file:com.udps.hive.jdbc.HiveConnection.java

public HiveConnection(String uri, Properties info) throws SQLException {
    setupLoginTimeout();/*w  w w.jav  a2s  . c  o m*/
    jdbcURI = uri;
    // parse the connection uri
    Utils.JdbcConnectionParams connParams;
    try {
        connParams = Utils.parseURL(uri);
    } catch (IllegalArgumentException e) {
        throw new SQLException(e);
    }
    // extract parsed connection parameters:
    // JDBC URL:
    // jdbc:hive2://<host>:<port>/dbName;sess_var_list?hive_conf_list#hive_var_list
    // each list: <key1>=<val1>;<key2>=<val2> and so on
    // sess_var_list -> sessConfMap
    // hive_conf_list -> hiveConfMap
    // hive_var_list -> hiveVarMap
    host = connParams.getHost();
    port = connParams.getPort();
    sessConfMap = connParams.getSessionVars();
    hiveConfMap = connParams.getHiveConfs();

    hiveVarMap = connParams.getHiveVars();
    for (Map.Entry<Object, Object> kv : info.entrySet()) {
        if ((kv.getKey() instanceof String)) {
            String key = (String) kv.getKey();
            if (key.startsWith(HIVE_VAR_PREFIX)) {
                hiveVarMap.put(key.substring(HIVE_VAR_PREFIX.length()), info.getProperty(key));
            } else if (key.startsWith(HIVE_CONF_PREFIX)) {
                hiveConfMap.put(key.substring(HIVE_CONF_PREFIX.length()), info.getProperty(key));
            }
        }
    }

    isEmbeddedMode = connParams.isEmbeddedMode();

    if (isEmbeddedMode) {
        client = new EmbeddedThriftBinaryCLIService();
    } else {
        // extract user/password from JDBC connection properties if its not
        // supplied in the
        // connection URL
        if (info.containsKey(HIVE_AUTH_USER)) {
            sessConfMap.put(HIVE_AUTH_USER, info.getProperty(HIVE_AUTH_USER));
            if (info.containsKey(HIVE_AUTH_PASSWD)) {
                sessConfMap.put(HIVE_AUTH_PASSWD, info.getProperty(HIVE_AUTH_PASSWD));
            }
        }
        if (info.containsKey(HIVE_AUTH_TYPE)) {
            sessConfMap.put(HIVE_AUTH_TYPE, info.getProperty(HIVE_AUTH_TYPE));
        }
        // open the client transport
        openTransport();
        // set up the client
        client = new TCLIService.Client(new TBinaryProtocol(transport));
    }

    // add supported protocols
    supportedProtocols.add(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V1);
    supportedProtocols.add(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V2);
    supportedProtocols.add(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V3);
    supportedProtocols.add(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V4);
    supportedProtocols.add(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V5);
    supportedProtocols.add(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V6);
    supportedProtocols.add(TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V7);

    // open client session
    openSession(connParams);
}