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:ca.qc.adinfo.rouge.variable.db.PersistentVariableDb.java

public static Variable getPersitentVariable(DBManager dbManager, String key) {

    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;

    String sql = "SELECT value, version FROM rouge_persistant_variable WHERE `key` = ?";

    try {/*from   ww w.  j a  va 2 s. co m*/
        connection = dbManager.getConnection();
        stmt = connection.prepareStatement(sql);

        stmt.setString(1, key);

        rs = stmt.executeQuery();

        if (rs.next()) {
            JSONObject jSonObject = JSONObject.fromObject(rs.getString("value"));

            return new Variable(key, new RougeObject(jSonObject), rs.getLong("version"));
        } else {
            return null;
        }

    } catch (SQLException e) {

        log.error(e);
        return null;

    } finally {

        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.sql.SystemEmail.java

/**
 * Gathers active email accounts for sending or receiving. 
 * // w  ww.  ja  va  2  s .co  m
 * @return
 */
public static boolean loadEmailConnectionInformation() {
    List<SystemEmailModel> systemEmailList = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT * FROM SystemEmail WHERE active = 1";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            SystemEmailModel row = new SystemEmailModel();
            row.setId(rs.getInt("id"));
            row.setActive(rs.getInt("active"));
            row.setSection(rs.getString("section"));
            row.setEmailAddress(rs.getString("emailAddress"));
            row.setUsername(rs.getString("username"));
            row.setPassword(rs.getString("password"));
            row.setIncomingURL(rs.getString("incomingURL"));
            row.setIncomingPort(rs.getInt("incomingPort"));
            row.setIncomingProtocol(rs.getString("incomingProtocol"));
            row.setIncomingFolder(rs.getString("incomingFolder"));
            row.setOutgoingURL(rs.getString("outgoingURL"));
            row.setOutgoingPort(rs.getInt("outgoingPort"));
            row.setOutgoingProtocol(rs.getString("outgoingProtocol"));
            row.setOutgoingFolder(rs.getString("outgoingFolder"));
            systemEmailList.add(row);
        }
        Global.setSystemEmailParams(systemEmailList);
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
        return false;
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return true;
}

From source file:FacultyAdvisement.StudentRepository.java

public static Map readAll(DataSource ds) throws SQLException {
    if (ds == null) {
        throw new SQLException("ds is null; Can't get data source");
    }//  w  w w  .  j a  va  2s. c o  m

    Connection conn = ds.getConnection();

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

    HashMap<String, Student> list = new HashMap<>();

    try {
        PreparedStatement ps = conn.prepareStatement("select * from STUDENT");

        // retrieve customer data from database
        ResultSet result = ps.executeQuery();

        while (result.next()) {
            Student s = new Student();
            s.setId(result.getString("STUID"));
            s.setUsername(result.getString("EMAIL"));
            s.setFirstName(result.getString("FIRSTNAME"));
            s.setLastName(result.getString("LASTNAME"));
            s.setMajorCode(result.getString("MAJORCODE"));
            s.setPhoneNumber(result.getString("PHONE"));
            if (result.getString("ADVISED").equals("true")) {
                s.setAdvised(true);
            } else {
                s.setAdvised(false);
            }
            list.put(s.getId(), s);
        }

    } finally {
        conn.close();
    }

    return list;
}

From source file:com.tethrnet.manage.db.SessionAuditDB.java

/**
 * returns terminal logs for user session for host system
 *
 * @param sessionId     session id//  w  ww .  jav  a  2  s.c om
 * @param instanceId    instance id for terminal session
 * @return session output for session
 */
public static List<SessionOutput> getTerminalLogsForSession(Connection con, Long sessionId,
        Integer instanceId) {

    List<SessionOutput> outputList = new LinkedList<SessionOutput>();
    try {
        PreparedStatement stmt = con.prepareStatement(
                "select * from terminal_log where instance_id=? and session_id=? order by log_tm asc");
        stmt.setLong(1, instanceId);
        stmt.setLong(2, sessionId);
        ResultSet rs = stmt.executeQuery();
        String output = "";
        while (rs.next()) {
            output = output + rs.getString("output");
        }

        output = output.replaceAll("\\u0007|\u001B\\[K|\\]0;|\\[\\d\\d;\\d\\dm|\\[\\dm", "");
        while (output.contains("\b")) {
            output = output.replaceFirst(".\b", "");
        }
        DBUtils.closeRs(rs);

        SessionOutput sessionOutput = new SessionOutput();
        sessionOutput.setSessionId(sessionId);
        sessionOutput.setInstanceId(instanceId);
        sessionOutput.getOutput().append(output);

        outputList.add(sessionOutput);

        DBUtils.closeRs(rs);

        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    return outputList;

}

From source file:edu.jhu.pha.vospace.oauth.MySQLOAuthProvider2.java

public static synchronized Token getAccessToken(final String tokenStr) {
    Token tokenObj = DbPoolServlet.goSql("Get oauth token",
            "select access_token, token_secret, consumer_key, callback_url, identity, container_name, accessor_write_permission, share_id "
                    + "from oauth_accessors "
                    + "join oauth_consumers on oauth_consumers.consumer_id = oauth_accessors.consumer_id "
                    + "left outer join containers on containers.container_id = oauth_accessors.container_id "
                    + "left outer join container_shares on oauth_accessors.share_key = container_shares.share_key "
                    + "left outer join users on users.user_id = containers.user_id "
                    + "left outer join user_identities on users.user_id = user_identities.user_id "
                    + "where access_token = ? limit 1",
            new SqlWorker<Token>() {
                @Override//from w  ww. ja  v  a2 s  .  c o m
                public Token go(Connection conn, PreparedStatement stmt) throws SQLException {
                    Token token = null;

                    stmt.setString(1, tokenStr);
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {

                        Set<USER_ROLES> rolesSet = new HashSet<USER_ROLES>();
                        if (null == rs.getString("share_id")) {
                            rolesSet.add(USER_ROLES.user);
                        } else {
                            if (rs.getBoolean("accessor_write_permission"))
                                rolesSet.add(USER_ROLES.rwshareuser);
                            else
                                rolesSet.add(USER_ROLES.roshareuser);
                        }
                        token = new Token(rs.getString("access_token"), rs.getString("token_secret"),
                                rs.getString("consumer_key"), rs.getString("callback_url"),
                                new SciDriveUser(rs.getString("identity"), rs.getString("container_name"),
                                        rs.getBoolean("accessor_write_permission")),
                                rolesSet, new MultivaluedMapImpl());

                    }
                    return token;
                }
            });

    return tokenObj;
}

From source file:com.wso2.raspberrypi.Util.java

private static RaspberryPi toRaspberryPi(ResultSet rs) throws SQLException {
    RaspberryPi pi = new RaspberryPi();
    pi.setMacAddress(rs.getString("mac"));
    pi.setIpAddress(rs.getString("ip"));
    pi.setLastUpdated(rs.getLong("last_updated"));
    pi.setLabel(rs.getString("label"));
    pi.setReservedFor(rs.getString("owner"));
    pi.setBlink(rs.getBoolean("blink"));
    pi.setReboot(rs.getBoolean("reboot"));
    pi.setSelected(rs.getBoolean("selected"));
    return pi;//from  w ww  . j a  v  a 2 s.  com
}

From source file:dbutils.ExampleJDBC.java

/**
 * Unlike some other classes in DbUtils, this class(SqlNullCheckedResultSet) is NOT thread-safe.
 *//*  www  .ja v  a2 s.  c om*/
public static void findUseSqlNullCheckedResultSet() {
    Connection conn = getConnection();
    try {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT id, name, gender, age, team_id as teamId FROM test_student");
        SqlNullCheckedResultSet wrapper = new SqlNullCheckedResultSet(rs);
        wrapper.setNullString("N/A"); // Set null string
        rs = ProxyFactory.instance().createResultSet(wrapper);

        while (rs.next()) {
            System.out.println("id=" + rs.getInt("id") + " username=" + rs.getString("name") + " gender="
                    + rs.getString("gender"));
        }
        rs.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        DbUtils.closeQuietly(conn);
    }
}

From source file:com.nortal.petit.converter.util.ResultSetHelper.java

@SuppressWarnings("unchecked")
public static <T> T get(Class<T> clazz, ResultSet rs, String column) throws SQLException {
    Converter<String, T> converter = ConverterFactory.getConverter(converterGroup, String.class, clazz);
    if (converter != null) {
        return converter.convert(rs.getString(column));
    }/* w  ww . j av a  2  s .co m*/

    return (T) getSimpleTyped(clazz, rs, column);
}

From source file:agendavital.modelo.data.Noticia.java

public static TreeMap<LocalDate, ArrayList<Noticia>> buscar(String _parametro)
        throws ConexionBDIncorrecta, SQLException {
    final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    ArrayList<String> _tags = UtilidadesBusqueda.separarPalabras(_parametro);
    TreeMap<LocalDate, ArrayList<Noticia>> busqueda = null;
    try (Connection conexion = ConfigBD.conectar()) {
        busqueda = new TreeMap<>();
        for (String _tag : _tags) {
            String tag = ConfigBD.String2Sql(_tag, true);
            String buscar = String.format("SELECT id_Noticia, fecha from noticias "
                    + "WHERE id_noticia IN (SELECT id_noticia from momentos_noticias_etiquetas "
                    + "WHERE id_etiqueta IN (SELECT id_etiqueta from etiquetas WHERE nombre LIKE %s)) "
                    + "OR titulo LIKE %s " + "OR cuerpo LIKE %s " + "OR categoria LIKE %s "
                    + "OR fecha LIKE %s; ", tag, tag, tag, tag, tag);
            ResultSet rs = conexion.createStatement().executeQuery(buscar);
            while (rs.next()) {
                LocalDate date = LocalDate.parse(rs.getString("fecha"), dateFormatter);
                Noticia insertarNoticia = new Noticia(rs.getInt("id_noticia"));
                if (busqueda.containsKey(date)) {
                    boolean encontrado = false;
                    for (int i = 0; i < busqueda.get(date).size() && !encontrado; i++)
                        if (busqueda.get(date).get(i).getId() == insertarNoticia.getId())
                            encontrado = true;
                    if (!encontrado)
                        busqueda.get(date).add(insertarNoticia);
                } else {
                    busqueda.put(date, new ArrayList<>());
                    busqueda.get(date).add(insertarNoticia);
                }//w  w  w . ja  v  a2 s. c om
            }

        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    Iterator it = busqueda.keySet().iterator();
    return busqueda;
}

From source file:application.gen.gen.java

public static List<Column> getColumns(Connection con, String catalog, String schema, String tableName)
        throws SQLException {
    List<Column> list = new ArrayList<Column>();
    ResultSet rs = con.getMetaData().getColumns(catalog, schema, tableName, "%");
    while (rs != null && rs.next()) {
        // System.out.println(rs.getString("COLUMN_NAME")+"
        // "+rs.getString("TYPE_NAME")+" "+rs.getString("COLUMN_SIZE")+"
        // "+rs.getString("NULLABLE"));
        Column column = new Column(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"),
                rs.getString("COLUMN_SIZE"), rs.getString("NULLABLE"));
        list.add(column);/*from   w  w  w.  j  a v  a 2s  .  c o  m*/
    }

    return list;
}