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.softberries.klerk.dao.PeopleDao.java

@Override
public void update(Person c) throws SQLException {
    try {// w ww  .  j  a  va 2s.co  m
        init();
        st = conn.prepareStatement(SQL_UPDATE_PERSON);
        st.setString(1, c.getFirstName());
        st.setString(2, c.getLastName());
        st.setString(3, c.getTelephone());
        st.setString(4, c.getMobile());
        st.setString(5, c.getEmail());
        st.setString(6, c.getWww());
        st.setLong(7, c.getId());
        // run the query
        int i = st.executeUpdate();
        System.out.println("i: " + i);
        if (i == -1) {
            System.out.println("db error : " + SQL_UPDATE_PERSON);
        }
        // delete unused addresses
        AddressDao adrDao = new AddressDao();
        List<Address> toDel = new ArrayList<Address>();
        if (c.getId() != null) {
            List<Address> existingAddresses = adrDao.findAllByCompanyId(c.getId(), run, conn);
            for (Address adr : existingAddresses) {
                if (!c.getAddresses().contains(adr)) {
                    toDel.add(adr);
                }
            }
        }
        for (Address adr : toDel) {
            adrDao.delete(adr.getId(), conn);
        }
        // update addresses
        for (Address adr : c.getAddresses()) {
            if (adr.getId() != null && adr.getId() > 0) {
                // update
                adrDao.update(adr, run, conn);
            } else {// create
                adr.setPerson_id(c.getId());
                adrDao.create(adr, 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:de.ufinke.cubaja.sql.ObjectFactoryGenerator.java

private void checkSetterMap(Class<?> clazz, WarnMode warnMode) throws SQLException {

    if (warnMode == WarnMode.IGNORE) {
        return;//  w ww  .j a v  a2  s.  c  o  m
    }

    for (SearchEntry entry : searchMap.values()) {
        if (!entry.setterFound) {
            switch (warnMode) {
            case WARN:
                logger.warn(text.get("noSetter", clazz.getName(), entry.name));
                break;
            case ERROR:
                throw new SQLException(text.get("noSetter", clazz.getName(), entry.name));
            case IGNORE:
                break;
            }
        }
    }
}

From source file:io.cloudslang.content.database.services.dbconnection.DBConnectionManager.java

/**
 * @param aDbType   one of the supported db type, for example ORACLE, NETCOOL
 * @param aDbUrl    connection url//w w  w . j ava 2s .c  o m
 * @param aUsername username to connect to db
 * @param aPassword password to connect to db
 * @return a Connection to db
 * @throws SQLException
 */
public synchronized Connection getConnection(DBType aDbType, String aAuthType, String aDbUrl, String aUsername,
        String aPassword, Properties properties) throws SQLException {
    if (isEmpty(aDbUrl)) {
        throw new SQLException("Failed to check out connection dbUrl is empty");
    }

    if (aDbType == null || !(MSSQL_DB_TYPE.equalsIgnoreCase(aDbType.toString())
            && AUTH_WINDOWS.equalsIgnoreCase(aAuthType))) {
        if (isEmpty(aUsername)) {
            throw new SQLException("Failed to check out connection,username is empty. dburl = " + aDbUrl);
        }

        if (isEmpty(aPassword)) {
            throw new SQLException("Failed to check out connection, password is empty. username = " + aUsername
                    + " dbUrl = " + aDbUrl);
        }
    }

    customizeDBConnectionManager(properties);

    if (!this.isPoolingEnabled) {
        //just call driver manager to create connection
        return this.getPlainConnection(aDbUrl, aUsername, aPassword);
    } else {
        //want connection pooling
        if (aDbType == null) {
            throw new SQLException("Failed to check out connection db type is null");
        }

        //if the runnable has been shutdown when dbmspoolsize is 0
        //then need to resumbit to the thread and start it again
        if (datasourceCleaner.getState() == STATE_CLEANER.SHUTDOWN) {
            //submit it to the thread to run
            cleanerThread = new Thread(datasourceCleaner);
            cleanerThread.setPriority(Thread.MIN_PRIORITY);
            cleanerThread.start();
        }
        //will use pooled datasource provider
        return getPooledConnection(aDbType, aDbUrl, aUsername, aPassword);
    }

}

From source file:com.ibatis.sqlmap.engine.mapping.statement.MappedStatement.java

public Object executeQueryForPaginatedCount(StatementScope statementScope, Transaction trans,
        Object parameterObject) throws SQLException {
    try {//from  w w  w .  j  a v a2 s . co  m
        Object object = null;

        DefaultRowHandler rowHandler = new DefaultRowHandler();
        executePaginatedCountWithCallback(statementScope, trans.getConnection(), parameterObject, null,
                rowHandler);
        List list = rowHandler.getList();
        if (list.size() > 1) {
            throw new SQLException("Error: executeQueryForObject returned too many results.");
        } else if (list.size() > 0) {
            object = list.get(0);
        }
        return object;
    } catch (TransactionException e) {
        throw new NestedSQLException("Error getting Connection from Transaction.  Cause: " + e, e);
    }
}

From source file:jef.database.DbUtils.java

/**
 * ?// www .  ja  va 2 s  . co  m
 * 
 * @param tasks
 * @throws SQLException
 */
public static void parallelExecute(List<DbTask> tasks) throws SQLException {
    CountDownLatch latch = new CountDownLatch(tasks.size());
    Queue<SQLException> exceptions = new ConcurrentLinkedQueue<SQLException>();
    Queue<Throwable> throwables = new ConcurrentLinkedQueue<Throwable>();
    for (DbTask task : tasks) {
        task.prepare(latch, exceptions, throwables);
        DbUtils.es.execute(task);
    }
    try {
        latch.await();
    } catch (InterruptedException e) {
        throw new SQLException(e);
    }
    if (!exceptions.isEmpty()) {
        throw DbUtils.wrapExceptions(exceptions);
    }
    if (!throwables.isEmpty()) {
        throw DbUtils.toRuntimeException(throwables.peek());
    }
}

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

@Override
public void update(Company c) throws SQLException {
    try {//from www  .  j a  v a  2 s .  com
        init();
        st = conn.prepareStatement(SQL_UPDATE_COMPANY);
        st.setString(1, c.getName());
        st.setString(2, c.getVatid());
        st.setString(3, c.getTelephone());
        st.setString(4, c.getMobile());
        st.setString(5, c.getEmail());
        st.setString(6, c.getWww());
        st.setLong(7, c.getId());
        // run the query
        int i = st.executeUpdate();
        System.out.println("i: " + i);
        if (i == -1) {
            System.out.println("db error : " + SQL_UPDATE_COMPANY);
        }

        // delete unused addresses
        AddressDao adrDao = new AddressDao();
        List<Address> toDel = new ArrayList<Address>();
        if (c.getId() != null) {
            List<Address> existingAddresses = adrDao.findAllByCompanyId(c.getId(), run, conn);
            for (Address adr : existingAddresses) {
                if (!c.getAddresses().contains(adr)) {
                    toDel.add(adr);
                }
            }
        }
        for (Address adr : toDel) {
            adrDao.delete(adr.getId(), conn);
        }
        // update addresses
        for (Address adr : c.getAddresses()) {
            if (adr.getId() != null && adr.getId() > 0) {
                // update
                adrDao.update(adr, run, conn);
            } else {// create
                adr.setCompany_id(c.getId());
                adrDao.create(adr, 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:FacultyAdvisement.StudentRepository.java

public static void updatePassword(DataSource ds, String username, String password) throws SQLException {

    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }//from   w w w.  java2  s.  com

    Connection conn = ds.getConnection();

    if (conn == null) {
        throw new SQLException("conn is null; Can't get db connection");
    }

    String newPassword = SHA256Encrypt.encrypt(password);
    try {
        PreparedStatement ps = conn.prepareStatement("Update USERTABLE set PASSWORD=? where USERNAME=?");
        ps.setString(1, newPassword);
        ps.setString(2, username);

        ps.executeUpdate();

    } finally {
        conn.close();
    }
}

From source file:it.larusba.neo4j.jdbc.http.HttpResultSet.java

@Override
public Array getArray(int columnIndex) throws SQLException {
    checkClosed();/*  w  w w .  j  a  va 2s  .  c o  m*/
    // 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)));
}

From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#retrieveMessages()
 *///from  w  w w.j  a v  a 2  s .co m
public synchronized List<Object[]> retrieveMessages() throws SQLException {
    final String methodName = IWebMessagingDAO.CNAME + "#retrieveMessages() throws SQLException";

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

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object[]> response = null;

    try {
        sqlConn = dataSource.getConnection();

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

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

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

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

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

            if (resultSet.next()) {
                resultSet.beforeFirst();
                response = new ArrayList<Object[]>();

                while (resultSet.next()) {
                    Object[] data = new Object[] { resultSet.getString(1), // svc_message_id
                            resultSet.getString(2), // svc_message_title
                            resultSet.getString(3), // svc_message_txt
                            resultSet.getString(4), // svc_message_author
                            resultSet.getTimestamp(5), // svc_message_submitdate
                            resultSet.getBoolean(6), // svc_message_active
                            resultSet.getBoolean(7), // svc_message_alert
                            resultSet.getBoolean(8), // svc_message_expires
                            resultSet.getTimestamp(9), // svc_message_expirydate
                            resultSet.getTimestamp(10), // svc_message_modifiedon
                            resultSet.getString(11) // svc_message_modifiedby
                    };

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

                    response.add(data);
                }
            }
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), 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 response;
}

From source file:com.app.dao.SearchQueryDAO.java

public SearchQuery getSearchQuery(int searchQueryId) throws DatabaseConnectionException, SQLException {

    _log.debug("Getting search query ID: {}", searchQueryId);

    try (Connection connection = DatabaseUtil.getDatabaseConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(_GET_SEARCH_QUERY_SQL)) {

        preparedStatement.setInt(1, searchQueryId);

        ResultSet resultSet = preparedStatement.executeQuery();

        if (resultSet.next()) {
            return _createSearchQueryFromResultSet(resultSet);
        } else {/*from  ww w  . j av a2 s. c  o m*/
            throw new SQLException("There is no search query for ID: " + searchQueryId);
        }
    }
}