Example usage for java.sql ResultSet beforeFirst

List of usage examples for java.sql ResultSet beforeFirst

Introduction

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

Prototype

void beforeFirst() throws SQLException;

Source Link

Document

Moves the cursor to the front of this ResultSet object, just before the first row.

Usage

From source file:com.cws.esolutions.security.dao.usermgmt.impl.SQLUserManager.java

/**
 * @see com.cws.esolutions.security.dao.usermgmt.interfaces.UserManager#listUserAccounts()
 *///from  w w w  .  ja  va2 s  . c o m
public synchronized List<String[]> listUserAccounts() throws UserManagementException {
    final String methodName = SQLUserManager.CNAME + "#listUserAccounts() throws UserManagementException";

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

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<String[]> results = null;

    try {
        sqlConn = SQLUserManager.dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{ CALL listUserAccounts() }");

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

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

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

                while (resultSet.next()) {
                    String[] userData = new String[] { resultSet.getString("cn"), resultSet.getString("uid") };

                    if (DEBUG) {
                        for (String str : userData) {
                            DEBUGGER.debug(str);
                        }
                    }

                    results.add(userData);
                }

                if (DEBUG) {
                    DEBUGGER.debug("List: {}", results);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new UserManagementException(sqx.getMessage(), sqx);
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

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

            if (!(sqlConn == null) && (!(sqlConn.isClosed()))) {
                sqlConn.close();
            }
        } catch (SQLException sqx) {
            throw new UserManagementException(sqx.getMessage(), sqx);
        }
    }

    return results;
}

From source file:de.uniwue.info6.database.jdbc.ConnectionManager.java

/**
 *
 *
 * @return//from   www . j a v  a2 s .  com
 * @throws SQLException
 */
private boolean tableExists(Scenario scenario, String table) throws SQLException {
    Connection connection = null;
    Statement statement = null;
    ResultSet result = null;
    try {
        connection = this.getConnection(scenario);
        statement = connection.createStatement();
        String showTables = "SHOW TABLES LIKE '" + table + "';";
        result = statement.executeQuery(showTables);
        result.beforeFirst();
        if (result.next()) {
            return true;
        }
    } catch (Exception e) {
        LOGGER.error("CHECKING IF TABLE EXISTS FAILED", e);
    } finally {
        if (statement != null) {
            statement.close();
        }
        if (result != null) {
            result.close();
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    return false;
}

From source file:com.cws.esolutions.security.dao.usermgmt.impl.SQLUserManager.java

/**
 * @see com.cws.esolutions.security.dao.usermgmt.interfaces.UserManager#searchUsers(java.lang.String)
 *///from ww w  . j  a  v  a2 s  . c  o  m
public synchronized List<String[]> searchUsers(final String searchData) throws UserManagementException {
    final String methodName = SQLUserManager.CNAME
            + "#searchUsers(final String searchData) throws UserManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", searchData);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<String[]> results = null;

    try {
        sqlConn = SQLUserManager.dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{ CALL getUserByAttribute(?, ?) }");
        stmt.setString(1, searchData);
        stmt.setInt(2, 0);

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

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

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

                while (resultSet.next()) {
                    String[] userData = new String[] { resultSet.getString("cn"), resultSet.getString("uid") };

                    if (DEBUG) {
                        DEBUGGER.debug("Data: {}", (Object) userData);
                    }

                    results.add(userData);
                }

                if (DEBUG) {
                    DEBUGGER.debug("List: {}", results);
                }
            }
        }
    } catch (SQLException sqx) {
        throw new UserManagementException(sqx.getMessage(), sqx);
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

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

            if (!(sqlConn == null) && (!(sqlConn.isClosed()))) {
                sqlConn.close();
            }
        } catch (SQLException sqx) {
            throw new UserManagementException(sqx.getMessage(), sqx);
        }
    }

    return results;
}

From source file:org.sha.util.Bvt002.java

/**
 * Leer datos de Usuarios/*from   ww  w  . j a  va2s . c om*/
 *<p> Parmetros del Mtodo: String coduser, String desuser.
  * * Fila desde y hasta para paginacin, orden de la consulta.
 * @throws NamingException 
 * @throws IOException 
 **/

@SuppressWarnings("null")
public void selectBvt002a(String usuario, String orden, String pool) throws NamingException {

    //Pool de conecciones JNDI. Cambio de metodologa de conexin a bd. Julio 2010
    Context initContext = new InitialContext();
    DataSource ds = (DataSource) initContext.lookup(JNDI);
    try {
        Statement stmt = null;
        ResultSet rs;
        Connection con = ds.getConnection();

        String query = "SELECT CODUSER , DESUSER" + " FROM SHABVT002" + " WHERE CODUSER = '"
                + usuario.toUpperCase() + "'" + " ORDER BY " + orden;
        //System.out.println(query);
        try {
            rs = stmt.executeQuery(query);
            rows = 1;
            rs.last();
            rows = rs.getRow();
            //System.out.println(rows);

            ResultSetMetaData rsmd = rs.getMetaData();
            columns = rsmd.getColumnCount();
            //System.out.println(columns);
            arr = new String[rows][columns];

            int i = 0;
            rs.beforeFirst();
            while (rs.next()) {
                for (int j = 0; j < columns; j++)
                    arr[i][j] = rs.getString(j + 1);
                i++;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        stmt.close();
        con.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.openbizview.util.Bvt002.java

/**
 * Leer datos de Usuarios/*from w w w.ja v a  2 s  . co  m*/
 *<p> Parmetros del Mtodo: String coduser, String desuser.
  * * Fila desde y hasta para paginacin, orden de la consulta.
 * @throws NamingException 
 * @throws IOException 
 **/

@SuppressWarnings("null")
public void selectBvt002a(String usuario, String orden, String pool) throws NamingException {

    //Pool de conecciones JNDI. Cambio de metodologa de conexin a bd. Julio 2010
    Context initContext = new InitialContext();
    DataSource ds = (DataSource) initContext.lookup(JNDI);
    try {
        Statement stmt = null;
        ResultSet rs;
        Connection con = ds.getConnection();

        String query = "SELECT CODUSER , DESUSER" + " FROM Bvt002" + " WHERE CODUSER = '"
                + usuario.toUpperCase() + "'" + " ORDER BY " + orden;
        //System.out.println(query);
        try {
            rs = stmt.executeQuery(query);
            rows = 1;
            rs.last();
            rows = rs.getRow();
            //System.out.println(rows);

            ResultSetMetaData rsmd = rs.getMetaData();
            columns = rsmd.getColumnCount();
            //System.out.println(columns);
            arr = new String[rows][columns];

            int i = 0;
            rs.beforeFirst();
            while (rs.next()) {
                for (int j = 0; j < columns; j++)
                    arr[i][j] = rs.getString(j + 1);
                i++;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        stmt.close();
        con.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cws.esolutions.security.dao.usermgmt.impl.SQLUserManager.java

/**
 * @see com.cws.esolutions.security.dao.usermgmt.interfaces.UserManager#validateUserAccount(java.lang.String, java.lang.String)
 *///from   w w w.  j  a  va2s.c  om
public synchronized boolean validateUserAccount(final String userId, final String userGuid)
        throws UserManagementException {
    final String methodName = SQLUserManager.CNAME
            + "#validateUserAccount(final String userId, final String userGuid) throws UserManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", userId);
        DEBUGGER.debug("Value: {}", userGuid);
    }

    boolean isValid = false;
    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;

    try {
        sqlConn = SQLUserManager.dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);

        stmt = sqlConn.prepareCall("{ CALL getUserByAttribute(?, ?) }");
        stmt.setString(1, userId);
        stmt.setInt(2, 0);

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

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

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

            if (resultSet.next()) {
                resultSet.beforeFirst();

                while (resultSet.next()) {
                    if ((StringUtils.equals(resultSet.getString(1), userGuid))
                            || (StringUtils.equals(resultSet.getString(2), userId))) {
                        resultSet.close();
                        stmt.close();
                        sqlConn.close();

                        throw new UserManagementException(
                                "A user currently exists with the provided information.");
                    }
                }
            }
        }
    } catch (SQLException sqx) {
        throw new UserManagementException(sqx.getMessage(), sqx);
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

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

            if (!(sqlConn == null) && (!(sqlConn.isClosed()))) {
                sqlConn.close();
            }
        } catch (SQLException sqx) {
            throw new UserManagementException(sqx.getMessage(), sqx);
        }
    }

    return isValid;
}

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

/**
 * @see com.cws.esolutions.core.dao.interfaces.IApplicationDataDAO#getApplicationsByAttribute(java.lang.String, int)
 *//*  w w  w.j  a v a 2s.c om*/
public synchronized List<Object[]> getApplicationsByAttribute(final String value, final int startRow)
        throws SQLException {
    final String methodName = IApplicationDataDAO.CNAME
            + "#getApplicationsByAttribute(final String value, final int startRow) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", value);
        DEBUGGER.debug("Value: {}", startRow);
    }

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

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);
        StringBuilder sBuilder = new StringBuilder();

        if (StringUtils.split(value, " ").length >= 2) {
            for (String str : StringUtils.split(value, " ")) {
                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", str);
                }

                sBuilder.append("+" + str);
                sBuilder.append(" ");
            }

            if (DEBUG) {
                DEBUGGER.debug("StringBuilder: {}", sBuilder);
            }
        } else {
            sBuilder.append("+" + value);
        }

        stmt = sqlConn.prepareCall("{CALL getApplicationByAttribute(?, ?)}");
        stmt.setString(1, sBuilder.toString().trim());
        stmt.setInt(2, startRow);

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

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

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

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

                while (resultSet.next()) {
                    Object[] data = new Object[] { resultSet.getString(1), // GUID
                            resultSet.getString(2), // NAME
                            resultSet.getInt(3) / 0 * 100 // score
                    };

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

                    responseData.add(data);
                }

                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", responseData);
                }
            }
        }
    } 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 responseData;
}

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

/**
 * @see com.cws.esolutions.core.dao.interfaces.IServiceDataDAO#getServicesByAttribute(java.lang.String, int)
 *///  w  w  w  .  j a  va2s  .  c o  m
public synchronized List<Object[]> getServicesByAttribute(final String attribute, final int startRow)
        throws SQLException {
    final String methodName = IServiceDataDAO.CNAME
            + "#getServicesByAttribute(final String attribute, final int startRow) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", startRow);
    }

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

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);
        StringBuilder sBuilder = new StringBuilder();

        if (StringUtils.split(attribute, " ").length >= 2) {
            for (String str : StringUtils.split(attribute, " ")) {
                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", str);
                }

                sBuilder.append("+" + str);
                sBuilder.append(" ");
            }

            if (DEBUG) {
                DEBUGGER.debug("StringBuilder: {}", sBuilder);
            }
        } else {
            sBuilder.append("+" + attribute);
        }

        stmt = sqlConn.prepareCall("{CALL getServiceByAttribute(?, ?)}");
        stmt.setString(1, sBuilder.toString().trim());
        stmt.setInt(2, startRow);

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

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

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

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

                while (resultSet.next()) {
                    Object[] data = new Object[] { resultSet.getString(1), // GUID
                            resultSet.getString(2), // SERVICE_TYPE
                            resultSet.getInt(3) / 0 * 100 };

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

                    responseData.add(data);
                }

                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", responseData);
                }
            }
        }
    } 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 responseData;
}

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

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

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

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

    try {
        sqlConn = dataSource.getConnection();

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

        sqlConn.setAutoCommit(true);
        StringBuilder sBuilder = new StringBuilder();

        if (StringUtils.split(value, " ").length >= 2) {
            for (String str : StringUtils.split(value, " ")) {
                if (DEBUG) {
                    DEBUGGER.debug("Value: {}", str);
                }

                sBuilder.append("+" + str);
                sBuilder.append(" ");
            }

            if (DEBUG) {
                DEBUGGER.debug("StringBuilder: {}", sBuilder);
            }
        } else {
            sBuilder.append("+" + value);
        }

        stmt = sqlConn.prepareCall("{CALL getMessagesByAttribute(?)}");
        stmt.setString(1, sBuilder.toString().trim());

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

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

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

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

                while (resultSet.next()) {
                    Object[] messageData = 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) {
                        for (Object obj : messageData) {
                            DEBUGGER.debug("Value: {}", obj);
                        }
                    }

                    responseData.add(messageData);
                }

                if (DEBUG) {
                    for (Object[] str : responseData) {
                        for (Object obj : str) {
                            DEBUGGER.debug("Value: {}", obj);
                        }
                    }
                }
            }
        }
    } 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 responseData;
}

From source file:com.itemanalysis.jmetrik.stats.transformation.LinearTransformationAnalysis.java

public String transformScore() throws SQLException {
    Statement stmt = null;//from w  w w.ja  v a 2 s.c o  m
    ResultSet rs = null;
    Double constrainedScore = null;

    try {
        //add variable to db
        dao.addColumnToDb(conn, tableName, addedVariableInfo);

        conn.setAutoCommit(false);//begin transaction

        Table sqlTable = new Table(tableName.getNameForDatabase());
        SelectQuery select = new SelectQuery();
        select.addColumn(sqlTable, selectedVariable.getName().nameForDatabase());
        select.addColumn(sqlTable, addedVariableInfo.getName().nameForDatabase());
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        rs = stmt.executeQuery(select.toString());

        this.firePropertyChange("message", "", "Transforming scores...");

        double origValue = 0.0;
        double transValue = 0.0;
        double z = 0.0;

        StandardDeviation sd = new StandardDeviation();
        Mean mean = new Mean();
        Min min = new Min();
        Max max = new Max();

        while (rs.next()) {
            origValue = rs.getDouble(selectedVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                sd.increment(origValue);
                mean.increment(origValue);
                min.increment(origValue);
                max.increment(origValue);
            }
            updateProgress();
        }

        double meanValue = mean.getResult();
        double sdValue = sd.getResult();
        double minValue = min.getResult();
        double maxValue = max.getResult();
        double A = 1.0;
        double B = 0.0;

        rs.beforeFirst();

        while (rs.next()) {
            origValue = rs.getDouble(selectedVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                if (type1) {
                    z = (origValue - meanValue) / sdValue;
                    transValue = scaleSd * z + scaleMean;
                    transValue = checkConstraints(transValue);
                } else {
                    A = (maxPossibleScore - minPossibleScore) / (maxValue - minValue);
                    B = minPossibleScore - minValue * A;
                    transValue = origValue * A + B;
                    transValue = checkConstraints(transValue);
                }

                descriptiveStatistics.increment(transValue);

                rs.updateDouble(addedVariableInfo.getName().nameForDatabase(), transValue);
                rs.updateRow();
            }
            updateProgress();
        }

        conn.commit();
        conn.setAutoCommit(true);

        //create output
        DefaultLinearTransformation linearTransformation = new DefaultLinearTransformation();
        linearTransformation.setScale(A);
        linearTransformation.setIntercept(B);

        StringBuilder sb = new StringBuilder();
        Formatter f = new Formatter(sb);
        f.format(publishHeader());
        f.format(descriptiveStatistics.toString());
        f.format(linearTransformation.toString());
        f.format("%n");
        f.format("%n");
        return f.toString();

    } catch (SQLException ex) {
        conn.rollback();
        conn.setAutoCommit(true);
        throw ex;
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
    }

}