Example usage for java.sql ResultSet toString

List of usage examples for java.sql ResultSet toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.tacitknowledge.util.migration.jdbc.util.SqlUtil.java

/**
 * Ensures the given connection, statement, and result are properly closed.
 *
 * @param conn the connection to close; may be <code>null</code>
 * @param stmt the statement to close; may be <code>null</code>
 * @param rs   the result set to close; may be <code>null</code>
 *///from  w w  w.  j av  a2 s .c  o m
public static void close(Connection conn, Statement stmt, ResultSet rs) {
    if (rs != null) {
        try {
            log.debug("Closing ResultSet: " + rs.toString());
            rs.close();
        } catch (SQLException e) {
            log.error("Error closing ResultSet", e);
        }
    }

    if (stmt != null) {
        try {
            log.debug("Closing Statement: " + stmt.toString());
            stmt.close();
        } catch (SQLException e) {
            log.error("Error closing Statement", e);
        }
    }

    if (conn != null) {
        try {
            if (!conn.isClosed()) {
                log.debug("Closing Connection " + conn.toString());
                conn.close();
            } else {
                log.debug("Connection (" + conn.toString() + ") already closed.");
            }
        } catch (SQLException e) {
            log.error("Error closing Connection", e);
        }
    }
}

From source file:canreg.client.dataentry.Convert.java

public static boolean convertData(canreg.client.gui.management.CanReg4MigrationInternalFrame.MigrationTask task,
        String filepath, String datafile, String regcode) {
    Connection conn;//from   www  .  java2  s . co m
    Statement stmt;
    ResultSet rs_hdr;
    ResultSet rs_data;
    boolean success = false;
    int totalrowcount = 0;
    int rowsImported = 0;

    String csv = filepath + Globals.FILE_SEPARATOR + regcode + ".csv";
    CSVPrinter printer;
    try {

        debugOut("Migrating data " + datafile);
        pconn = (ParadoxConnection) DriverManager
                .getConnection("jdbc:paradox:///" + filepath.replaceAll("\\\\", "/"));
        final ParadoxTable table = TableData.listTables(pconn, datafile).get(0);
        totalrowcount = table.getRowCount();

        SystemDescription sd = new SystemDescription(
                Globals.CANREG_SERVER_SYSTEM_CONFIG_FOLDER + Globals.FILE_SEPARATOR + regcode + ".xml");
        DatabaseVariablesListElement[] variableListElements;
        variableListElements = sd.getDatabaseVariableListElements();
        ArrayList<String> dbvle = new ArrayList();
        ArrayList<String> cols = new ArrayList();

        // Handling variables names with reservered word by replacing underscore after variable name.
        for (DatabaseVariablesListElement variable : variableListElements) {
            if (variable.getShortName().endsWith("_")) {
                dbvle.add(variable.getShortName().replace("_", ""));
            } else {
                dbvle.add(variable.getShortName());
            }
        }

        conn = DriverManager.getConnection("jdbc:paradox:///" + filepath.replaceAll("\\\\", "/"));

        final DatabaseMetaData meta = conn.getMetaData();
        rs_hdr = meta.getColumns("", "", datafile, "%");

        //Comparing variables in file and database
        while (rs_hdr.next()) {
            for (String dbvar : dbvle) {
                if (rs_hdr.getString("COLUMN_NAME").equals(dbvar)
                        || rs_hdr.getString("COLUMN_NAME").replaceAll(" ", "_").equals(dbvar)) {
                    cols.add(rs_hdr.getString("COLUMN_NAME"));
                }
            }
        }

        String[] strheader = new String[cols.size()];

        String query = "SELECT ";

        for (int i = 0; i < cols.size(); i++) {
            strheader[i] = cols.get(i).toString();
            if (i == cols.size() - 1) {
                query += "\"" + strheader[i] + "\"";
            } else {
                query += "\"" + strheader[i] + "\",";
            }
        }

        query += " FROM  \"" + datafile + "\"";
        CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withHeader(strheader).withDelimiter(',');

        debugOut(query);
        printer = new CSVPrinter(new FileWriter(csv), format);

        int hdrsize = strheader.length;

        Object[] strdata = new String[hdrsize];

        stmt = conn.createStatement();
        rs_data = stmt.executeQuery(query);

        if (Globals.DEBUG) {
            Statement stmt2 = conn.createStatement();
            String q = "SELECT RecNum FROM \"" + datafile + "\"";
            ResultSet rs_all_data = stmt2.executeQuery(q);
            debugOut(rs_all_data.toString());
        }

        while (rs_data.next()) {
            for (int i = 1; i < rs_data.getMetaData().getColumnCount() + 1; i++) {
                switch (rs_data.getMetaData().getColumnType(i)) {
                case 4:
                    strdata[i - 1] = Integer.toString(rs_data.getShort(i));
                    break;
                case 12:
                    strdata[i - 1] = StringEscapeUtils.escapeCsv(rs_data.getString(i));
                    break;
                }
            }
            printer.printRecord(strdata);
            rowsImported++;
        }
        printer.flush();
        printer.close();
        success = true;
    } catch (SQLException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null, ex);
    }
    success = success && (rowsImported == totalrowcount);
    return success;
}

From source file:RetriveBody.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    refnumber = request.getParameter("refno");
    branch = request.getParameter("branch");
    tID = request.getParameter("tid");
    PrintWriter out = response.getWriter();
    HttpSession sess = request.getSession(false);
    String session = sess.getAttribute("name").toString();
    JSONObject tdata = new JSONObject();
    if (session.length() != 0) {
        try {/*from   w ww.j  a  v a  2  s  . com*/
            try {
                String JDBC_DRIVER = "com.mysql.jdbc.Driver";

                Class.forName(JDBC_DRIVER);
                PreparedStatement ps, ps1;
                Connection con = DriverManager.getConnection(Keys.dbText, Keys.dbID, Keys.dbPass);
                ps = con.prepareStatement(
                        "select body from notice_" + branch.toLowerCase() + " where reference_no=?");
                ps1 = con.prepareStatement("select fname,email,pno from faculty where fid=?");
                ps.setString(1, refnumber);
                ps1.setString(1, tID);
                ResultSet rs = ps.executeQuery();
                ResultSet rs1 = ps1.executeQuery();
                if (rs.toString().length() != 0) {
                    while (rs.next()) {
                        body = rs.getString(1);
                    }
                    //out.write(body);
                }
                if (rs1.toString().length() != 0) {
                    while (rs1.next()) {
                        gettID = rs1.getString(1);
                        getemail = rs1.getString(2);
                        getmobile = rs1.getString(3);
                    }
                    tdata.put("body", body);
                    tdata.put("fname", gettID);
                    tdata.put("fmail", getemail);
                    tdata.put("fmobile", getmobile);
                    out.write(tdata.toString());
                    ps.close();
                    ps1.close();
                    con.close();
                    rs.close();
                    rs1.close();
                }
            } catch (Exception e) {
            }

        } catch (Exception e) {

        }
    } else {
        out.write("Session Expired!!!");
    }
}

From source file:com.github.heartsemma.enderauth.Database.java

/**@param uuid (Universally Unique Identifier)
 * @return A boolean//from  w ww  . j a va 2 s  .c om
 * 
 * <br><Br>Returns true if there is an entry in the User Table with a uuid matching the parameter. 
 * <br>Returns false if there is not.
 * 
 * @throws SQLException The function uses PreparedStatements to ask about the presence of the UUID in the User Table.
 * @throws DatabaseException If the returned ResultSet from the SELECT command is completely empty (that is, lacking even the names of the columns in the table), the function throws a DatabaseException.*/
public boolean isInDatabase(byte[] uuid) throws SQLException, DatabaseException {
    logger.debug("Attempting to determine presence of user " + new String(uuid) + " in the database.");

    String isInDatabaseCommand = "SELECT * FROM ? WHERE ? = ?";

    ArrayList<Object> isInDatabaseVariables = new ArrayList<Object>();

    isInDatabaseVariables.add(1, userTableName);
    isInDatabaseVariables.add(2, userTableIDColumn);
    isInDatabaseVariables.add(3, uuid);

    //Command should look something like: SELECT * FROM ea_users WHERE id == uuid

    ResultSet selection = transact(isInDatabaseCommand, isInDatabaseVariables);

    logger.debug("Database inquiry returned the ResultSet: " + selection.toString() + ".");

    logger.debug("Error Checking...");
    Preconditions.checkNotNull(selection);

    //ResultSet Analysis + Error Checking
    if (selection.isBeforeFirst()) { //Triggers when there are no rows in the ResultSet.
        logger.error("EnderAuth attempted to find if there was a uuid matching " + new String(uuid)
                + " in the database but was unable to run the necessary SQL queries.");
        logger.error(
                "There were no rows in the returned table of data after running the MySql 'PreparedStatement'.");
        throw new DatabaseException("Returned ResultSet in isPresent(String uuid) contained no rows.");
    }

    selection.last();

    if (selection.getRow() == 1) { //There are no entries in the ResultSet.
        logger.debug("No entries for user " + new String(uuid) + " were found in the ResultSet.");
        return false;

    } else { //There is one or more entries with the matching uuid.
        logger.debug("User " + new String(uuid) + " was found in the database.");
        return true;
    }

}

From source file:com.github.heartsemma.enderauth.Database.java

/**
 * @param uuid (Universally Unique Identifier)
 * @return The Pre-Shared Key of the user for their TOTP authentication.
 * /*from   w  w  w.j a v a  2 s. c o m*/
 * <br><br>Returns the TOTP Pre-Shared Key connected with the specified UUID.
 * <br>Returns null if unable to retrieve the key (if not found or  
 * 
 * @throws SQLException This function accesses the database via a "SELECT" query.
 * @throws DatabaseException Thrown if the returned ResultSet contains missing or what should be erroneous data.
 */
public String getTotpKey(byte[] uuid) throws SQLException, DatabaseException {
    logger.debug("Attempting to retrieve TOTP PSK for user " + new String(uuid) + ".");

    String getKeyCommand = "SELECT ? FROM ? WHERE ? == ?";

    ArrayList<Object> getKeyVariables = new ArrayList<Object>();
    getKeyVariables.add(userTableTotpPSKColumn);
    getKeyVariables.add(userTableName);
    getKeyVariables.add(userTableIDColumn);
    getKeyVariables.add(uuid);

    ResultSet selection = transact(getKeyCommand, getKeyVariables);

    logger.debug("Database inquiry returned the ResultSet: " + selection.toString() + ".");

    //There should be one String in this resultset, but we will check it good because EnderAuth is stronk, EnderAuth is reliable.
    logger.debug("Error checking...");
    Preconditions.checkNotNull(selection);

    if (!selection.isBeforeFirst()) { //Triggers when there are no rows in the ResultSet.
        logger.error("EnderAuth attempted to retrieve " + new String(uuid)
                + "'s PSK from the database but was unable to find it.");
        logger.error(
                "There were no rows in the returned table of data after running the MySql 'PreparedStatement' .");

        throw new DatabaseException("getTotpKey()'s PreparedStatement returned a ResultSet that had no data.");
    }

    selection.last();

    if (selection.getRow() == 1) { //There was no entry for this user.
        logger.error("EnderAuth attempted to retrieve " + new String(uuid)
                + "'s PSK from the database but was unable to find it.");
        logger.error("Does " + new String(uuid) + " have an entry in the " + userTableName + " table?");

        //Returns null because we were unable to get the required data.
        throw new UUIDNotFoundException(
                "getTotpKey() was unable to find the entry in the database with the specified UUID.");

    } else if (selection.getRow() == 2) { //There was one entry for this user
        //If we get to this point, everything looks tight.   
        logger.debug("Successfully retrieved PSK from user " + new String(uuid) + ".");

        String PSK = selection.getString(userTableTotpPSKColumnIndex);
        return PSK;

    } else { //There was more than one entry for this user.
        logger.error("EnderAuth searched for " + new String(uuid)
                + "'s PSK and found multiple entries for that user in the database.");
        logger.error(
                "This should not have happened and indicates either plugin glitches or malcious database tampering.");

        throw new DatabaseException("Multiple entries matching the specified UUID were found in the database.");
    }
}

From source file:Server.Service.JDBCMemoryDatabaseService.java

protected ArrayList<String> getNames() throws SQLException {
    try {//from   w w w  . jav  a  2s  . co  m
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT username FROM users");
        ResultSet resultSet = preparedStatement.executeQuery();
        System.out.println(resultSet.toString());
        List<String> names = new ArrayList<>();
        while (resultSet.next()) {
            String actualName = resultSet.getString("username");
            names.add(actualName);
            System.out.println(actualName);
        }
        return (ArrayList<String>) names;
    } catch (SQLException e) {
        return null;
    }
}

From source file:Server.Service.JDBCMemoryDatabaseService.java

protected ArrayList<String> getCurrentUsers() throws SQLException {
    try {/*w  w w .ja  va  2 s  .c o  m*/
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT username FROM CURRENTUSERS");
        ResultSet resultSet = preparedStatement.executeQuery();
        System.out.println(resultSet.toString());
        List<String> names = new ArrayList<>();
        while (resultSet.next()) {
            String actualName = resultSet.getString("username");
            names.add(actualName);
            System.out.println(actualName);
        }
        return (ArrayList<String>) names;
    } catch (SQLException e) {
        e.printStackTrace();
        return new ArrayList<>();
    }
}

From source file:org.apache.tajo.QueryTestCaseBase.java

public static QueryId getQueryId(ResultSet resultSet) {
    if (resultSet instanceof TajoMemoryResultSet) {
        return ((TajoMemoryResultSet) resultSet).getQueryId();
    } else if (resultSet instanceof FetchResultSet) {
        return ((FetchResultSet) resultSet).getQueryId();
    } else {/*from  ww  w. ja va  2 s.  c o m*/
        throw new IllegalArgumentException(resultSet.toString());
    }
}

From source file:org.kew.rmf.core.lucene.LuceneDataLoader.java

/**
 * Adds a single record to the Lucene index
 * @param record//from w  w w.  j  a v  a 2 s  .  com
 * @throws Exception
 */
private Document indexRecord(ResultSet record) throws Exception {
    Document doc = new Document();
    String idFieldName = Configuration.ID_FIELD_NAME;
    logger.trace("rawRecord: {}", record.toString());

    doc.add(new StringField(idFieldName, record.getString(idFieldName), Field.Store.YES));

    // The remainder of the columns are added as specified in the properties
    for (Property p : this.config.getProperties()) {
        String authorityName = p.getAuthorityColumnName() + Configuration.TRANSFORMED_SUFFIX;
        String value = record.getString(p.getAuthorityColumnName());
        if (value == null)
            value = "";

        // Index the value in its original state, pre transformation
        Field f = new TextField(p.getAuthorityColumnName(), value, Field.Store.YES);
        doc.add(f);

        // then transform the value if necessary
        for (Transformer t : p.getAuthorityTransformers()) {
            value = t.transform(value);
        }
        // and add this one to the index
        Field fTransformed = new TextField(authorityName, value, Field.Store.YES);
        doc.add(fTransformed);

        // For some fields (those which will be passed into a fuzzy matcher like Levenshtein), we index the length
        if (p.isIndexLength()) {
            Field fLength = new StringField(authorityName + Configuration.LENGTH_SUFFIX,
                    String.format("%02d", value.length()), Field.Store.YES);
            doc.add(fLength);
        }

        if (p.isIndexInitial() & StringUtils.isNotBlank(value)) {
            Field finit = new TextField(authorityName + Configuration.INITIAL_SUFFIX, value.substring(0, 1),
                    Field.Store.YES);
            doc.add(finit);
        }
    }

    logger.trace("Document to be indexed: {}", doc.toString());
    this.indexWriter.addDocument(doc);
    return doc;
}

From source file:storybook.model.oldModel.ModelMigration.java

/**
 * Closes the result set/*  w w  w  .  j  a va  2s  .c o  m*/
 *
 * @param result The ResultSet that needs to close
 */
public void closeResultSet(ResultSet result) {
    try {
        if (result != null) {
            result.close();
        }
    } catch (SQLException se) {
        SbApp.error("*** ModelMigration.closeResultSet(" + result.toString() + ")", se);
    }
}