Example usage for java.sql ResultSet getTimestamp

List of usage examples for java.sql ResultSet getTimestamp

Introduction

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

Prototype

java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

From source file:com.sfs.whichdoctor.dao.WhichDoctorDAOImpl.java

private WhichDoctorBean loadBean(final ResultSet rs) throws SQLException {

    final WhichDoctorBean loadedBean = new WhichDoctorBean();

    loadedBean.setGUID(rs.getInt("GUID"));
    loadedBean.setObjectType(rs.getString("ObjectType"));
    try {//from  w ww .j  av a 2s . c  o  m
        loadedBean.setCreatedDate(rs.getTimestamp("CreatedDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage());
    }
    loadedBean.setCreatedBy(rs.getString("CreatedBy"));
    try {
        loadedBean.setModifiedDate(rs.getTimestamp("ModifiedDate"));
    } catch (SQLException sqe) {
        dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage());
    }
    loadedBean.setModifiedBy(rs.getString("ModifiedBy"));

    return loadedBean;
}

From source file:mupomat.controller.ObradaKorisnik.java

public List<Korisnik> dohvatiNeaktivnogKorisnika(String uvjet) {
    List<Korisnik> lista = new ArrayList<>();
    try {//from  ww  w  .j  a v a 2s.co  m
        Connection veza = MySqlBazaPodataka.getConnection();
        PreparedStatement izraz = veza.prepareStatement(
                "select a.sifra,a.datumregistracije,a.korisnickoime,a.uloga,a.aktivan, b.* from korisnik a inner join osoba b on a.oib=b.oib where b.ime like  ? and aktivan=0");
        izraz.setString(1, "%" + uvjet + "%");
        //            izraz.setString(2, "%" + uvjet + "%");

        ResultSet rs = izraz.executeQuery();
        Korisnik entitet = null;
        while (rs.next()) {
            //System.out.println("evo me");
            entitet = new Korisnik();
            entitet.setSifra(rs.getInt("sifra"));
            entitet.setIme(rs.getString("ime"));
            entitet.setPrezime(rs.getString("prezime"));
            entitet.setOib(rs.getString("oib"));
            entitet.setEmail(rs.getString("email"));
            entitet.setDatumRegistracije(new Date(rs.getTimestamp("datumregistracije").getTime()));
            entitet.setKorisnickoIme(rs.getString("korisnickoime"));
            entitet.setUloga(rs.getString("uloga"));
            entitet.setAktivan(rs.getBoolean("aktivan"));

            lista.add(entitet);

        }
        rs.close();
        izraz.close();
        veza.close();
    } catch (Exception e) {

        e.printStackTrace();
        return null;
    }

    return lista;
}

From source file:mupomat.controller.ObradaKorisnik.java

@Override
public List<Korisnik> dohvatiIzBaze(String uvjet) {
    List<Korisnik> lista = new ArrayList<>();
    try {//from   w ww . j av  a  2s .  co  m
        Connection veza = MySqlBazaPodataka.getConnection();
        PreparedStatement izraz = veza.prepareStatement(
                "select a.sifra,a.datumregistracije,a.korisnickoime,a.uloga,a.aktivan, b.* from korisnik a inner join osoba b on a.oib=b.oib where b.ime like  ? and aktivan=1");
        izraz.setString(1, "%" + uvjet + "%");
        //            izraz.setString(2, "%" + uvjet + "%");

        ResultSet rs = izraz.executeQuery();
        Korisnik entitet = null;
        while (rs.next()) {
            //System.out.println("evo me");
            entitet = new Korisnik();
            entitet.setSifra(rs.getInt("sifra"));
            entitet.setIme(rs.getString("ime"));
            entitet.setPrezime(rs.getString("prezime"));
            entitet.setOib(rs.getString("oib"));
            entitet.setEmail(rs.getString("email"));
            entitet.setDatumRegistracije(new Date(rs.getTimestamp("datumregistracije").getTime()));
            entitet.setKorisnickoIme(rs.getString("korisnickoime"));
            entitet.setUloga(rs.getString("uloga"));
            entitet.setAktivan(rs.getBoolean("aktivan"));

            lista.add(entitet);

        }
        rs.close();
        izraz.close();
        veza.close();
    } catch (Exception e) {

        e.printStackTrace();
        return null;
    }

    return lista;
}

From source file:mysql5.MySQL5PlayerDAO.java

@Override
public Timestamp getCharacterCreationDateId(final int obj) {
    Connection con = null;//from w  ww .  j  a v  a  2  s  . c  o  m
    Timestamp creationDate;
    try {
        con = DatabaseFactory.getConnection();
        PreparedStatement s = con.prepareStatement("SELECT `creation_date` FROM `players` WHERE `id` = ?");
        s.setInt(1, obj);
        ResultSet rs = s.executeQuery();
        rs.next();
        creationDate = rs.getTimestamp("creation_date");
        rs.close();
        s.close();
    } catch (Exception e) {
        return null;
    } finally {
        DatabaseFactory.close(con);
    }
    return creationDate;
}

From source file:cc.cicadabear.security.infrastructure.jdbc.OauthClientDetailsRowMapper.java

@Override
public OauthClientDetails mapRow(ResultSet rs, int i) throws SQLException {
    OauthClientDetails clientDetails = new OauthClientDetails();

    clientDetails.clientId(rs.getString("client_id"));
    clientDetails.resourceIds(rs.getString("resource_ids"));
    clientDetails.clientSecret(rs.getString("client_secret"));

    clientDetails.scope(rs.getString("scope"));
    clientDetails.authorizedGrantTypes(rs.getString("authorized_grant_types"));
    clientDetails.webServerRedirectUri(rs.getString("web_server_redirect_uri"));

    clientDetails.authorities(rs.getString("authorities"));
    clientDetails.accessTokenValidity(getInteger(rs, "access_token_validity"));
    clientDetails.refreshTokenValidity(getInteger(rs, "refresh_token_validity"));

    clientDetails.additionalInformation(rs.getString("additional_information"));
    clientDetails.createTime(rs.getTimestamp("create_time").toLocalDateTime());
    clientDetails.archived(rs.getBoolean("archived"));

    clientDetails.trusted(rs.getBoolean("trusted"));
    clientDetails.autoApprove(rs.getString("autoapprove"));

    return clientDetails;
}

From source file:com.concursive.connect.web.modules.profile.dao.ProjectIndexer.java

/**
 * Given a database and an indexer, this method will add content to the
 * searchable index//from ww  w . j a va 2s.  c o m
 *
 * @param writer  Description of the Parameter
 * @param db      Description of the Parameter
 * @param context Servlet context
 * @throws SQLException Description of the Exception
 * @throws IOException  Description of the Exception
 */
public void add(IIndexerService writer, Connection db, IndexerContext context) throws Exception {
    long startTime = System.currentTimeMillis();
    int count = 0;
    PreparedStatement pst = db.prepareStatement(
            "SELECT instance_id, project_id, title, shortdescription, description, requestedby, requesteddept, entered, modified, "
                    + "category_id, subcategory1_id, "
                    + "allow_guests, membership_required, allows_user_observers, approvaldate, closedate, portal, "
                    + "city, state, postalcode, keywords, " + "rating_count, rating_value, rating_avg "
                    + "FROM projects " + "WHERE project_id > -1 ");
    ResultSet rs = pst.executeQuery();
    while (rs.next() && context.getEnabled()) {
        ++count;
        // read the record
        Project project = new Project();
        project.setInstanceId(rs.getInt("instance_id"));
        project.setId(rs.getInt("project_id"));
        project.setTitle(rs.getString("title"));
        project.setShortDescription(rs.getString("shortdescription"));
        project.setDescription(rs.getString("description"));
        project.setRequestedBy(rs.getString("requestedby"));
        project.setRequestedByDept(rs.getString("requesteddept"));
        project.setEntered(rs.getTimestamp("entered"));
        project.setModified(rs.getTimestamp("modified"));
        project.setCategoryId(DatabaseUtils.getInt(rs, "category_id"));
        project.setSubCategory1Id(DatabaseUtils.getInt(rs, "subcategory1_id"));
        project.getFeatures().setAllowGuests(rs.getBoolean("allow_guests"));
        project.getFeatures().setMembershipRequired(rs.getBoolean("membership_required"));
        project.getFeatures().setAllowParticipants(rs.getBoolean("allows_user_observers"));
        project.setApprovalDate(rs.getTimestamp("approvaldate"));
        if (project.getApprovalDate() != null) {
            project.setApproved(true);
        }
        project.setCloseDate(rs.getTimestamp("closedate"));
        if (project.getCloseDate() != null) {
            project.setClosed(true);
        }
        project.setPortal(rs.getBoolean("portal"));
        project.setCity(rs.getString("city"));
        project.setState(rs.getString("state"));
        project.setPostalCode(rs.getString("postalcode"));
        project.setKeywords(rs.getString("keywords"));
        project.setRatingCount(rs.getInt("rating_count"));
        project.setRatingValue(rs.getInt("rating_value"));
        project.setRatingAverage((rs.getDouble("rating_avg")));
        // add the document
        if (writer instanceof LuceneIndexer) {
            LuceneIndexer luceneWriter = (LuceneIndexer) writer;
            luceneWriter.indexAddItem(project, false, context.getIndexType());
        } else {
            // Don't know specifically what to do...
            writer.indexAddItem(project, false);
        }
    }
    rs.close();
    pst.close();
    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    LOG.info("Finished: " + count + " took " + totalTime + " ms");
}

From source file:com.its.core.local.hezhou.task.ExportImageFilesReadTaskNew.java

private List<VehicelRecordBean> getExportRecordList(Connection conn) throws Exception {
    List<VehicelRecordBean> recordList = new ArrayList<VehicelRecordBean>();
    PreparedStatement preStatement = null;
    ResultSet rs = null;
    try {//from w  ww .j av  a  2 s.c  om
        //         log.debug(""+this.getSelecImageFileRecordSql());
        preStatement = conn.prepareStatement(this.getSelecImageFileRecordSql());
        rs = preStatement.executeQuery();

        while (rs.next()) {
            VehicelRecordBean record = new VehicelRecordBean();
            record.setId(rs.getLong("ID"));
            record.setDeviceIp(rs.getString("DeviceIP"));
            record.setPlate(rs.getString("LicenseNumber"));
            record.setPlateColorCode(rs.getString("LicenseColor"));
            record.setDirectionCode(rs.getString("Direction"));
            record.setCatchTime(rs.getTimestamp("CatchDate"));
            record.setDrivewayNo(rs.getString("RoadId"));
            record.setSpeed(rs.getString("Speed"));
            record.setFeatureImagePath(rs.getString("ImagePath"));
            recordList.add(record);
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        throw ex;
    } finally {
        DatabaseHelper.close(rs, preStatement);
    }
    return recordList;
}

From source file:edu.corgi.uco.UserBean.java

public AppointmentEvent getAppointment() {
    String user = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
    try (Connection conn = dataSource.getConnection()) {
        PreparedStatement query = conn.prepareStatement("select userid from usertable where email = ?",
                Statement.RETURN_GENERATED_KEYS);

        query.setString(1, user);/*  ww  w  .j  av a 2 s . c  om*/
        ResultSet rs = query.executeQuery();
        int uid = 0;
        if (rs.next()) {
            uid = rs.getInt(1);
        }

        query = conn.prepareStatement(
                "select * from appointment natural join appointment_slots " + "where userid = ?",
                Statement.RETURN_GENERATED_KEYS);
        query.setInt(1, uid);
        rs = query.executeQuery();

        AppointmentEvent ae;
        Timestamp sd = null;
        Timestamp ed = null;
        if (rs.next()) {
            sd = rs.getTimestamp("startdate");
            ed = rs.getTimestamp("enddate");
        }

        ae = new AppointmentEvent("Student Event", sd, ed, 0);

        return ae;
    } catch (SQLException ex) {
        Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:edu.ku.brc.specify.config.FixDBAfterLogin.java

/**
 * /*w w  w  . j a  va 2  s .c  om*/
 */
public static void fixUserPermissions(final boolean doSilently) {
    final String FIXED_USER_PERMS = "FIXED_USER_PERMS";
    boolean isAlreadyFixed = AppPreferences.getRemote().getBoolean(FIXED_USER_PERMS, false);
    if (isAlreadyFixed) {
        return;
    }

    String whereStr = " WHERE p.GroupSubClass = 'edu.ku.brc.af.auth.specify.principal.UserPrincipal' ";
    String whereStr2 = "AND p.userGroupScopeID IS NULL";

    String postSQL = " FROM specifyuser su "
            + "INNER JOIN specifyuser_spprincipal ss ON su.SpecifyUserID = ss.SpecifyUserID "
            + "INNER JOIN spprincipal p ON ss.SpPrincipalID = p.SpPrincipalID "
            + "LEFT JOIN spprincipal_sppermission pp ON p.SpPrincipalID = pp.SpPrincipalID "
            + "LEFT OUTER JOIN sppermission pm ON pp.SpPermissionID = pm.SpPermissionID " + whereStr;

    String sql = "SELECT COUNT(*)" + postSQL + whereStr2;
    log.debug(sql);
    if (BasicSQLUtils.getCountAsInt(sql) < 1) {
        sql = "SELECT COUNT(*)" + postSQL;
        log.debug(sql);
        if (BasicSQLUtils.getCountAsInt(sql) > 0) {
            return;
        }
    }

    final String updatePermSQL = "DELETE FROM %s WHERE SpPermissionID = %d";
    final String updatePrinSQL = "DELETE FROM %s WHERE SpPrincipalID = %d";

    sql = "SELECT p.SpPrincipalID, pp.SpPermissionID" + postSQL;
    log.debug(sql);

    HashSet<Integer> prinIds = new HashSet<Integer>();
    for (Object[] row : query(sql)) {
        Integer prinId = (Integer) row[0];
        if (prinId != null) {
            prinIds.add(prinId);
        }

        Integer permId = (Integer) row[1];
        if (permId != null) {
            update(String.format(updatePermSQL, "spprincipal_sppermission", permId));
            update(String.format(updatePermSQL, "sppermission", permId));
            log.debug("Removing PermId: " + permId);
        }
    }

    StringBuilder sb1 = new StringBuilder();
    for (Integer prinId : prinIds) {
        update(String.format(updatePrinSQL, "specifyuser_spprincipal", prinId));
        update(String.format(updatePrinSQL, "spprincipal", prinId));
        log.debug("Removing PrinId: " + prinId);
        if (sb1.length() > 0)
            sb1.append(",");
        sb1.append(prinId.toString());
    }
    log.debug("(" + sb1.toString() + ")");

    // Create all the necessary UperPrincipal records
    // Start by figuring out what group there are and then create one UserPrincipal record
    // for each one

    TreeSet<String> nameSet = new TreeSet<String>();
    sql = "SELECT su.Name, su.SpecifyUserID, p.userGroupScopeID, p.SpPrincipalID FROM specifyuser su "
            + "INNER JOIN specifyuser_spprincipal sp ON su.SpecifyUserID = sp.SpecifyUserID "
            + "INNER JOIN spprincipal p ON sp.SpPrincipalID = p.SpPrincipalID "
            + "WHERE p.GroupSubClass = 'edu.ku.brc.af.auth.specify.principal.GroupPrincipal'";

    String fields = "TimestampCreated, TimestampModified, Version, GroupSubClass, groupType, Name, Priority, Remarks, userGroupScopeID, CreatedByAgentID, ModifiedByAgentID";
    String insertSQL = "INSERT INTO spprincipal (" + fields + ") VALUES(?,?,?,?,?,?,?,?,?,?,?)";
    String insertSQL2 = "INSERT INTO specifyuser_spprincipal (SpecifyUserID, SpPrincipalID) VALUES(?,?)";

    String searchSql = "SELECT " + fields + " FROM spprincipal WHERE SpPrincipalID = ?";

    sb1 = new StringBuilder();

    PreparedStatement selStmt = null;
    PreparedStatement pStmt = null;
    PreparedStatement pStmt2 = null;
    try {
        Connection conn = DBConnection.getInstance().getConnection();

        pStmt = conn.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
        pStmt2 = conn.prepareStatement(insertSQL2);
        selStmt = conn.prepareStatement(searchSql);

        String adtSQL = "SELECT DISTINCT ca.AgentID FROM specifyuser AS su INNER Join agent AS ca ON su.CreatedByAgentID = ca.AgentID";
        Integer createdById = BasicSQLUtils.getCount(conn, adtSQL);
        if (createdById == null) {
            createdById = BasicSQLUtils.getCount(conn,
                    "SELECT AgentID FROM agent ORDER BY AgentID ASC LIMIT 0,1");
            if (createdById == null) {
                UIRegistry.showError("The permissions could not be fixed because there were no agents.");
                AppPreferences.shutdownAllPrefs();
                DBConnection.shutdownFinalConnection(true, true);
                return;
            }
        }

        for (Object[] row : query(sql)) {
            String usrName = (String) row[0];
            Integer userId = (Integer) row[1];
            Integer collId = (Integer) row[2];
            Integer prinId = (Integer) row[3];

            nameSet.add(usrName);

            log.debug("usrName: " + usrName + "  prinId: " + prinId);
            if (sb1.length() > 0)
                sb1.append(",");
            sb1.append(prinId.toString());

            selStmt.setInt(1, prinId);
            ResultSet rs = selStmt.executeQuery();
            if (rs.next()) {
                log.debug(String.format("%s - adding UserPrincipal for Collection  %d / %d", usrName,
                        rs.getInt(9), collId));
                Integer createdByAgentID = (Integer) rs.getObject(10);
                Integer modifiedByAgentID = (Integer) rs.getObject(11);

                pStmt.setTimestamp(1, rs.getTimestamp(1));
                pStmt.setTimestamp(2, rs.getTimestamp(2));
                pStmt.setInt(3, 1); // Version
                pStmt.setString(4, "edu.ku.brc.af.auth.specify.principal.UserPrincipal"); // GroupSubClass
                pStmt.setString(5, null); // groupType
                pStmt.setString(6, rs.getString(6)); // Name
                pStmt.setInt(7, 80); // Priority
                pStmt.setString(8, rs.getString(8)); // Remarks
                pStmt.setInt(9, rs.getInt(9)); // userGroupScopeID
                pStmt.setInt(10, createdByAgentID != null ? createdByAgentID : createdById);
                pStmt.setInt(11, modifiedByAgentID != null ? modifiedByAgentID : createdById);

                // Create UserPrincipal
                pStmt.executeUpdate();

                int newPrinId = BasicSQLUtils.getInsertedId(pStmt);

                // Join the new Principal to the SpecifyUser record
                pStmt2.setInt(1, userId);
                pStmt2.setInt(2, newPrinId);
                pStmt2.executeUpdate();

            } else {
                // error
            }
            rs.close();
        }

        log.debug("(" + sb1.toString() + ")");

        AppPreferences.getRemote().putBoolean(FIXED_USER_PERMS, true);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (pStmt != null)
                pStmt.close();
            if (pStmt2 != null)
                pStmt2.close();
            if (selStmt != null)
                selStmt.close();
        } catch (Exception ex) {
        }
    }

    final StringBuilder sb = new StringBuilder();
    for (String nm : nameSet) {
        if (sb.length() > 0)
            sb.append('\n');
        sb.append(nm);
    }

    if (!doSilently) {
        JTextArea ta = UIHelper.createTextArea(15, 30);
        ta.setText(sb.toString());
        ta.setEditable(false);

        JEditorPane htmlPane = new JEditorPane("text/html", //$NON-NLS-1$
                UIRegistry.getResourceString("FDBAL_PERMFIXEDDESC"));
        htmlPane.setEditable(false);
        htmlPane.setOpaque(false);

        CellConstraints cc = new CellConstraints();
        PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p:g,8px,f:p:g"));
        pb.add(htmlPane, cc.xy(1, 1));
        pb.add(UIHelper.createScrollPane(ta), cc.xy(1, 3));
        pb.setDefaultDialogBorder();

        CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(),
                UIRegistry.getResourceString("FDBAL_PERMFIXED"), true, CustomDialog.OK_BTN, pb.getPanel());
        dlg.setOkLabel(UIRegistry.getResourceString("CLOSE"));
        UIHelper.centerAndShow(dlg);
    }
}

From source file:eu.celarcloud.jcatascopia.web.queryMaster.database.MySQL.DBInterfaceWithConnPool.java

public ArrayList<AgentObj> getAgentsWithTimestamps(String status) {
    String query = "SELECT * FROM agent_table";
    PreparedStatement stmt = null;
    Connection c = null;//from  w w w .j  av a  2  s  .co m
    try {
        query += (status == null || status.length() == 0) ? "" : " WHERE status='" + status + "'";

        c = this.getConnection();
        stmt = c.prepareStatement(query);
        ResultSet rs = stmt.executeQuery();
        ArrayList<AgentObj> agentlist = new ArrayList<AgentObj>();
        String tstart;
        AgentObj agent;
        while (rs.next()) {
            agent = new AgentObj(rs.getString("agentID"), rs.getString("agentIP"), rs.getString("status"));
            agentlist.add(agent);
            tstart = Long.toString(rs.getTimestamp("tstart").getTime() / 1000);
            agent.setTstart(tstart);
            if (rs.getTimestamp("tstop") != null)
                agent.setTstop(Long.toString(rs.getTimestamp("tstop").getTime() / 1000));
            agent.setAgentName(rs.getString("agentName"));
            agent.setTags(rs.getString("tags"));
        }
        return agentlist;
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        this.release(stmt, c);
    }
    return null;
}