Example usage for java.sql ResultSet getString

List of usage examples for java.sql ResultSet getString

Introduction

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

Prototype

String getString(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.

Usage

From source file:hnu.helper.DataBaseConnection.java

/**
 * Returns a String containing all values of a row of a resultset.
 * rs: the Data-ResultsSet<br />//w  w  w.  j av  a 2s. c o  m
 * row: which row of the ResultSet rs should be used<br />
 * brackets: if true, method surround the string with brackets<br />
 * This method can be used with workarounds for sub-selects with MySQL.<br />
 *<br />
 * Example:<br />
 * getValuesStringFromResultSet(rs, 1, true) returns<br />
 * "('123','23455','2341','1234')"<br />
 */
public static String getValuesStringFromResultSet(ResultSet rs, int row, boolean brackets) {
    String tempStr = new String("");

    try {
        if (rs.next()) {
            if (brackets) {
                tempStr = "(";
            }

            tempStr += ("'" + rs.getString(row) + "'");
        } else {
            if (brackets) {
                return "('')";
            } else {
                return "''";
            }
        }

        while (rs.next()) {
            tempStr += (",'" + rs.getString(row) + "'");
        }

        if (brackets) {
            return tempStr + ")";
        } else {
            return tempStr;
        }
    } catch (Exception ex) {
        return "('')";
    }
}

From source file:com.keybox.manage.db.UserDB.java

/**
 * returns all admin users based on sort order defined
 * @param sortedSet object that defines sort order
 * @return sorted user list//from  w ww .  ja  va2  s  .  c o  m
 */
public static SortedSet getAdminUserSet(SortedSet sortedSet) {

    ArrayList<User> userList = new ArrayList<>();

    String orderBy = "";
    if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) {
        orderBy = "order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection();
    }
    String sql = "select * from  users where enabled=true and user_type like '" + User.ADMINISTRATOR + "' "
            + orderBy;

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setFirstNm(rs.getString(FIRST_NM));
            user.setLastNm(rs.getString(LAST_NM));
            user.setEmail(rs.getString(EMAIL));
            user.setUsername(rs.getString(USERNAME));
            user.setPassword(rs.getString(PASSWORD));
            user.setAuthType(rs.getString(AUTH_TYPE));
            user.setUserType(rs.getString(USER_TYPE));
            userList.add(user);

        }
        DBUtils.closeRs(rs);
        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    DBUtils.closeConn(con);

    sortedSet.setItemList(userList);
    return sortedSet;
}

From source file:edu.jhu.pha.vospace.jobs.JobsProcessor.java

/**
 * Returns the JobDescription object serialized from the database record
 * @param jobId The identifier of a job//from w  w w.  j  a  v a 2s  . co  m
 * @return The job java object
 */
public static JobDescription getJob(final UUID jobId) {
    return DbPoolServlet.goSql("GetJob request", "select json_notation, note from jobs where id = ?",
            new SqlWorker<JobDescription>() {
                @Override
                public JobDescription go(Connection conn, PreparedStatement stmt) throws SQLException {
                    JobDescription returnJob = null;
                    stmt.setString(1, jobId.toString());
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        byte[] jobJsonNotation = rs.getBytes(1);
                        try {
                            returnJob = (new ObjectMapper()).readValue(jobJsonNotation, 0,
                                    jobJsonNotation.length, JobDescription.class);
                            returnJob.setNote(rs.getString("note"));
                        } catch (JsonMappingException ex) { // Shouldn't happen
                            throw new InternalServerErrorException(ex.getMessage());
                        } catch (JsonParseException ex) {
                            throw new InternalServerErrorException(ex.getMessage());
                        } catch (IOException ex) {
                            throw new InternalServerErrorException(ex.getMessage());
                        }
                    }
                    return returnJob;
                }
            });
}

From source file:com.sql.CaseType.java

/**
 * Gathers a list of active case types for finding the proper section based 
 * on the case number.//from   w w w . j  av  a2s. c  o m
 * 
 * @param section For which section the method is currently processing
 * @return List CaseTypeModel
 */
public static List<CaseTypeModel> getCaseTypesBySection(String section) {
    List<CaseTypeModel> list = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT * FROM CaseType WHERE active = 1 AND section = ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1, section);
        rs = ps.executeQuery();
        while (rs.next()) {
            CaseTypeModel item = new CaseTypeModel();
            item.setId(rs.getInt("id"));
            item.setActive(rs.getBoolean("active"));
            item.setSection(rs.getString("Section"));
            item.setCaseType(rs.getString("caseType"));
            item.setDescription(rs.getString("Description"));
            list.add(item);
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return list;
}

From source file:de.unibremen.informatik.tdki.combo.ui.CommandComplete.java

private static void dropFilter(String namePattern) {
    // TODO: add a stored procedure for filter dropping
    try {/*from  w  ww .  ja  v a2  s.com*/
        final QueryRunner qRunner = new QueryRunner();
        qRunner.query(
                "SELECT funcname, parm_count FROM Syscat.Functions WHERE funcname LIKE '" + namePattern + "%'",
                new RowCallbackHandler() {

                    @Override
                    public void processRow(ResultSet rs) throws SQLException {
                        StringBuilder query = new StringBuilder();
                        query.append("DROP FUNCTION ").append(rs.getString(1)).append("(");
                        int noOfParams = rs.getInt(2);
                        for (int i = 0; i < noOfParams; i++) {
                            query.append("INTEGER");
                            if (i != noOfParams - 1) {
                                query.append(",");
                            }
                        }
                        query.append(")");
                        qRunner.update(connection, query.toString());
                    }
                });
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.zenoss.zep.dao.impl.DaoUtils.java

/**
 * Returns a list of column names in the specified table.
 *
 * @param dataSource DataSource to use./*from  w w  w.  j  ava2  s  . c  om*/
 * @param tableName Table name.
 * @return A list of column names in the table.
 * @throws MetaDataAccessException If an exception occurs.
 */
public static List<String> getColumnNames(final javax.sql.DataSource dataSource, final String tableName)
        throws MetaDataAccessException {
    final List<String> columnNames = new ArrayList<String>();
    JdbcUtils.extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() {
        @Override
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            ResultSet rs = dbmd.getColumns(null, null, tableName, null);
            while (rs.next()) {
                String columnName = rs.getString("COLUMN_NAME");
                columnNames.add(columnName);
            }
            rs.close();
            return null;
        }
    });
    return columnNames;
}

From source file:com.netradius.hibernate.support.HibernateUtil.java

private static List<String[]> getTables() {
    final List<String[]> rows = new ArrayList<String[]>();
    rows.add(new String[] { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE", "REMARKS", "TYPE_CAT",
            "TYPE_SCHEM", "TYPE_NAME", "SELF_REFERENCING_COL_NAME", "REF_GENERATION " });
    Connection con = null;/*from  w ww . j av a  2  s  . co m*/
    ResultSet rs = null;
    try {
        con = getConnection();
        final DatabaseMetaData md = con.getMetaData();
        rs = md.getTables(null, null, "%", null);
        while (rs.next()) {
            List<String> s = new ArrayList<String>(10);
            for (int i = 10; i > 0; i--)
                s.add(rs.getString(i));
            rows.add(s.toArray(new String[10]));
        }
    } catch (SQLException x) {
        log.error("Error listing tables: " + x.getMessage(), x);
    } finally {
        close(con, null, rs);
    }
    return rows;
}

From source file:com.sql.EmailOutAttachment.java

/**
 * Gathers a list of attachments for a specific email address.
 * /*from  w  w  w  .j a v a  2s .c om*/
 * @param emailID Integer
 * @return List (EmailOutAttachmentModel) 
 */
public static List<EmailOutAttachmentModel> getAttachmentsByEmail(int emailID) {
    List<EmailOutAttachmentModel> list = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT * FROM EmailOutAttachment WHERE emailOutID = ?";
        ps = conn.prepareStatement(sql);
        ps.setInt(1, emailID);
        rs = ps.executeQuery();
        while (rs.next()) {
            EmailOutAttachmentModel item = new EmailOutAttachmentModel();
            item.setId(rs.getInt("id"));
            item.setEmailOutID(rs.getInt("emailOutID"));
            item.setFileName(rs.getString("fileName"));
            list.add(item);
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return list;
}

From source file:org.zenoss.zep.dao.impl.DaoUtils.java

/**
 * Returns a map of column names to their JDBC type in the specified table. The map is returned in the order
 * returned by the getColumns query.//from   www  .  j  a  v a 2s .c  o  m
 *
 * @param dataSource DataSource to use.
 * @param tableName Table name.
 * @return A map of column names to the column types in the specified table.
 * @throws MetaDataAccessException If an exception occurs.
 */
public static Map<String, Integer> getColumnNamesAndTypes(final DataSource dataSource, final String tableName)
        throws MetaDataAccessException {
    final Map<String, Integer> columnNamesToTypes = new LinkedHashMap<String, Integer>();
    JdbcUtils.extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() {
        @Override
        public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
            ResultSet rs = dbmd.getColumns(null, null, tableName, null);
            while (rs.next()) {
                String columnName = rs.getString("COLUMN_NAME");
                int columnType = rs.getInt("DATA_TYPE");
                columnNamesToTypes.put(columnName, columnType);
            }
            rs.close();
            return null;
        }
    });
    return columnNamesToTypes;
}

From source file:com.netradius.hibernate.support.HibernateUtil.java

private static List<String[]> getColumns(final String table) {
    final List<String[]> rows = new ArrayList<String[]>();
    rows.add(new String[] { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME",
            "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "NUM_PREC_RADIX", "NULLABLE", "REMARKS",
            "COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION",
            "IS_NULLABLE", "SCOPE_CATLOG", "SCOPE_SCHEMA", "SCOPE_TABLE", "SOURCE_DATA_TYPE",
            "IS_AUTOINCREMENT" });
    Connection con = null;//from  ww  w .ja v  a  2 s .co m
    ResultSet rs = null;
    try {
        con = getConnection();
        final DatabaseMetaData md = con.getMetaData();
        rs = md.getColumns(null, null, table, "%");
        while (rs.next()) {
            List<String> s = new ArrayList<String>(23);
            for (int i = 23; i > 0; i--)
                s.add(rs.getString(i));
            rows.add(s.toArray(new String[23]));
        }
    } catch (SQLException x) {
        log.error("Error describing table: " + x.getMessage(), x);
    } finally {
        close(con, null, rs);
    }
    return rows;
}