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:jp.primecloud.auto.tool.management.zabbix.ZabbixSqlService.java

public String getUser(String username) throws SQLException, Exception {

    String getUserSql = "select alias from users where alias='" + username + "'";
    String nameResult = "";
    try {/*ww w  .  ja  v  a2 s.c  o  m*/
        Object result = sqlExecuter.getColumn(getUserSql, "alias", "string");
        if (result != null) {
            nameResult = result.toString();
        }
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        throw new SQLException(e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new Exception(e);
    }
    return nameResult;
}

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

@Override
public void delete(Long id) throws SQLException {
    try {//from w  w  w  . j a  va 2s.  co  m
        init();
        st = conn.prepareStatement(SQL_DELETE_PRODUCT);
        st.setLong(1, id);
        // run the query
        int i = st.executeUpdate();
        System.out.println("i: " + i);
        if (i == -1) {
            System.out.println("db error : " + SQL_DELETE_PRODUCT);
        }
        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:org.jtalks.poulpe.util.databasebackup.persistence.DbTableKeys.java

/**
 * Obtain from the database a list of tables' unique keys.
 * /*  w ww . ja v  a2  s . c  o m*/
 * @return A list of {@link UniqueKey} object represented unique keys.
 * @throws SQLException
 *             Is thrown in case any errors during work with database occur.
 */
@SuppressWarnings("unchecked")
public Set<UniqueKey> getUniqueKeys() throws SQLException {
    Set<UniqueKey> tableUniqueKeySet = null;
    try {
        tableUniqueKeySet = (Set<UniqueKey>) JdbcUtils.extractDatabaseMetaData(dataSource,
                new KeyListProcessor(tableName, new TableKeyPerformer() {
                    @Override
                    public ResultSet getResultSet(DatabaseMetaData dmd, String tableName) throws SQLException {
                        return dmd.getIndexInfo(null, null, tableName, true, true);
                    }

                    @Override
                    public void addKeyToSet(ResultSet rs, Set<TableKey> keySet) throws SQLException {
                        if (rs.getString(INDEX_NAME) != null && rs.getString(COLUMN_NAME) != null) {
                            UniqueKey key = new UniqueKey(rs.getString(INDEX_NAME), rs.getString(COLUMN_NAME));
                            if (!isPrimaryKey(key)) {
                                keySet.add(key);
                            }
                        }

                    }
                }));

        Map<String, UniqueKey> resultMap = new HashMap<String, UniqueKey>();
        for (UniqueKey uniqueKey : tableUniqueKeySet) {
            if (resultMap.containsKey(uniqueKey.getIndexName())) {
                Set<String> existingColumns = new HashSet<String>(
                        resultMap.get(uniqueKey.getIndexName()).getColumnNameSet());
                existingColumns.addAll(uniqueKey.getColumnNameSet());
                resultMap.put(uniqueKey.getIndexName(),
                        new UniqueKey(uniqueKey.getIndexName(), existingColumns));
            } else {
                resultMap.put(uniqueKey.getIndexName(), uniqueKey);
            }
        }
        tableUniqueKeySet.clear();
        for (UniqueKey key : resultMap.values()) {
            tableUniqueKeySet.add(key);
        }

    } catch (MetaDataAccessException e) {
        throw new SQLException(e);
    }
    return tableUniqueKeySet;
}

From source file:org.apache.jena.jdbc.remote.connections.RemoteEndpointConnection.java

/**
 * Creates a new remote connection//from  w  ww .j a v a2s.c om
 * 
 * @param queryEndpoint
 *            SPARQL Query Endpoint
 * @param updateEndpoint
 *            SPARQL Update Endpoint
 * @param defaultGraphUris
 *            Default Graph URIs for SPARQL queries
 * @param namedGraphUris
 *            Named Graph URIs for SPARQL queries
 * @param usingGraphUris
 *            Default Graph URIs for SPARQL updates
 * @param usingNamedGraphUris
 *            Named Graph URIs for SPARQL updates
 * @param client
 *            HTTP client
 * @param holdability
 *            Result Set holdability
 * @param compatibilityLevel
 *            JDBC compatibility level, see {@link JdbcCompatibility}
 * @param selectResultsType
 *            Results Type to request for {@code SELECT} queries against the
 *            remote endpoint
 * @param modelResultsType
 *            Results Type to request for {@code CONSTRUCT} and
 *            {@code DESCRIBE} queries against the remote endpoint
 * @throws SQLException
 *             Thrown if there is a problem creating the connection
 */
public RemoteEndpointConnection(String queryEndpoint, String updateEndpoint, List<String> defaultGraphUris,
        List<String> namedGraphUris, List<String> usingGraphUris, List<String> usingNamedGraphUris,
        HttpClient client, int holdability, int compatibilityLevel, String selectResultsType,
        String modelResultsType) throws SQLException {
    super(holdability, true, Connection.TRANSACTION_NONE, compatibilityLevel);
    if (queryEndpoint == null && updateEndpoint == null)
        throw new SQLException("Must specify one/both of a query endpoint and update endpoint");
    this.queryService = queryEndpoint;
    this.updateService = updateEndpoint;
    this.readonly = this.updateService == null;
    this.defaultGraphUris = defaultGraphUris;
    this.namedGraphUris = namedGraphUris;
    this.usingGraphUris = usingGraphUris;
    this.usingNamedGraphUris = usingNamedGraphUris;
    this.client = client;
    this.metadata = new RemoteEndpointMetadata(this);
    this.selectResultsType = selectResultsType;
    this.modelResultsType = modelResultsType;
}

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

public void create(DocumentItem c, QueryRunner run, Connection conn, ResultSet generatedKeys)
        throws SQLException {
    PreparedStatement st = conn.prepareStatement(SQL_INSERT_DOCUMENTITEM, Statement.RETURN_GENERATED_KEYS);
    st.setString(1, c.getPriceNetSingle());
    st.setString(2, c.getPriceGrossSingle());
    st.setString(3, c.getPriceTaxSingle());
    st.setString(4, c.getPriceNetAll());
    st.setString(5, c.getPriceGrossAll());
    st.setString(6, c.getPriceTaxAll());
    st.setString(7, c.getTaxValue());/*from   ww  w  .j  a  va 2 s. c om*/
    st.setString(8, c.getQuantity());
    if (c.getProduct().getId().longValue() == 0 && c.getDocument_id().longValue() == 0) {
        throw new SQLException(
                "For DocumentItem corresponding product and document it belongs to need to be specified");
    }
    if (c.getProduct().getId() != 0) {
        st.setLong(9, c.getProduct().getId());
    } else {
        st.setNull(9, java.sql.Types.NUMERIC);
    }
    if (c.getDocument_id().longValue() != 0) {
        st.setLong(10, c.getDocument_id());
    } else {
        st.setNull(10, java.sql.Types.NUMERIC);
    }
    st.setString(11, c.getProduct().getName());
    // run the query
    int i = st.executeUpdate();
    System.out.println("i: " + i);
    if (i == -1) {
        System.out.println("db error : " + SQL_INSERT_DOCUMENTITEM);
    }
    generatedKeys = st.getGeneratedKeys();
    if (generatedKeys.next()) {
        c.setId(generatedKeys.getLong(1));
    } else {
        throw new SQLException("Creating user failed, no generated key obtained.");
    }
}

From source file:com.taobao.tddl.jdbc.group.TGroupPreparedStatement.java

public boolean execute() throws SQLException {
    if (log.isDebugEnabled()) {
        log.debug("invoke execute, sql = " + sql);
    }/*from  w w w.j a  va  2 s.  co m*/

    SqlType sqlType = SQLParser.getSqlType(sql);
    if (sqlType == SqlType.SELECT || sqlType == SqlType.SELECT_FOR_UPDATE || sqlType == SqlType.SHOW) {
        executeQuery();
        return true;
    } else if (sqlType == SqlType.INSERT || sqlType == SqlType.UPDATE || sqlType == SqlType.DELETE
            || sqlType == SqlType.REPLACE || sqlType == SqlType.TRUNCATE || sqlType == SqlType.CREATE
            || sqlType == SqlType.DROP || sqlType == SqlType.LOAD || sqlType == SqlType.MERGE) {
        super.updateCount = executeUpdate();
        return false;
    } else {
        throw new SQLException(
                "only select, insert, update, delete,truncate,create,drop,load,merge sql is supported");
    }
}

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

@Override
public void create(Company c) throws SQLException {
    try {/*from  w ww  .  ja v  a  2 s .co  m*/
        init();
        st = conn.prepareStatement(SQL_INSERT_COMPANY, Statement.RETURN_GENERATED_KEYS);
        st.setString(1, c.getName());
        st.setString(2, c.getVatid());
        st.setString(3, c.getTelephone());
        st.setString(4, c.getTelephone());
        st.setString(5, c.getTelephone());
        st.setString(6, c.getTelephone());
        // run the query
        int i = st.executeUpdate();
        System.out.println("i: " + i);
        if (i == -1) {
            System.out.println("db error : " + SQL_INSERT_COMPANY);
        }
        generatedKeys = st.getGeneratedKeys();
        if (generatedKeys.next()) {
            c.setId(generatedKeys.getLong(1));
        } else {
            throw new SQLException("Creating company failed, no generated key obtained.");
        }
        // if the company creation was successfull, add addresses
        AddressDao adrDao = new AddressDao();
        for (Address adr : c.getAddresses()) {
            adr.setCompany_id(c.getId());
            adrDao.create(adr, run, conn, generatedKeys);
            if (adr.isMain()) {
                c.setAddress(adr);
            }
        }
        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:jp.primecloud.auto.tool.management.db.SQLExecuter.java

public void executePrepared(String sql, String... params) throws SQLException, Exception {
    Connection con = null;// www  .j a  va  2s  . c o  m
    PreparedStatement ps = null;
    ResultSet rs = null;
    // ??
    String logSQL = passwordMask(sql);
    log.info("[" + logSQL + "] ???");
    try {
        con = dbConnector.getConnection();
        ps = con.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            ps.setString(i + 1, params[i]);
        }
        ps.execute();
        log.info("[" + logSQL + "] ????");
    } catch (SQLException e) {
        log.error(passwordMask(e.getMessage()), e);
        throw new SQLException(e);
    } catch (Exception e) {
        log.error(passwordMask(e.getMessage()), e);
        throw new Exception(e);
    } finally {
        try {
            dbConnector.closeConnection(con, ps, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

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

/**
 * @see com.cws.esolutions.security.dao.reference.interfaces.ISecurityReferenceDAO#obtainSecurityQuestionList()
 *///from  ww w.j  a  v  a2  s .c om
public synchronized List<String> obtainSecurityQuestionList() throws SQLException {
    final String methodName = ISecurityReferenceDAO.CNAME + "#obtainSecurityQuestionList() throws SQLException";

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

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<String> questionList = null;

    try {
        sqlConn = dataSource.getConnection();

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

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

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

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();
            resultSet.last();
            int iRowCount = resultSet.getRow();

            if (iRowCount == 0) {
                throw new SQLException("No security questions are currently configured.");
            }

            resultSet.first();
            ResultSetMetaData resultData = resultSet.getMetaData();

            int iColumns = resultData.getColumnCount();

            questionList = new ArrayList<String>();

            for (int x = 1; x < iColumns + 1; x++) {
                if (DEBUG) {
                    DEBUGGER.debug("resultSet.getObject: {}", resultSet.getObject(resultData.getColumnName(x)));
                }

                // check if column is null
                resultSet.getObject(resultData.getColumnName(x));

                // if the column was null, insert n/a, otherwise, insert the column's contents
                questionList.add((String) (resultSet.wasNull() ? "N/A"
                        : resultSet.getObject(resultData.getColumnName(x))));
            }
        }
    } 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 questionList;
}

From source file:at.alladin.rmbt.db.dao.QoSTestResultDao.java

@Override
public List<QoSTestResult> getAll() throws SQLException {
    List<QoSTestResult> resultList = new ArrayList<>();

    try (PreparedStatement psGetAll = conn.prepareStatement(
            "SELECT nntr.uid, test_uid, nnto.test, success_count, failure_count, result AS result, "
                    + " nnto.results as results, qos_test_uid, nnto.test_desc, nnto.test_summary FROM qos_test_result nntr "
                    + " JOIN qos_test_objective nnto ON nntr.qos_test_uid = nnto.uid")) {
        if (psGetAll.execute()) {
            try (ResultSet rs = psGetAll.getResultSet()) {
                while (rs.next()) {
                    resultList.add(instantiateItem(rs));
                }//w  ww.j  av  a 2  s  . com
            }
        } else {
            throw new SQLException("item not found");
        }

        return resultList;
    }
}