Example usage for java.sql PreparedStatement executeQuery

List of usage examples for java.sql PreparedStatement executeQuery

Introduction

In this page you can find the example usage for java.sql PreparedStatement executeQuery.

Prototype

ResultSet executeQuery() throws SQLException;

Source Link

Document

Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

Usage

From source file:dao.CarryonEntryIdQuery.java

public List run(Connection conn, String loginid) {
    String sqlQuery = "select entryid from carryon where loginid=" + loginid
            + " order by entrydate DESC limit 1";
    try {//w  w w .jav a  2s  .  c  om
        PreparedStatement stmt = conn.prepareStatement(sqlQuery);
        ResultSet rs = stmt.executeQuery();

        Vector columnNames = null;
        Photo photo = null;
        List photosList = new ArrayList();

        if (rs != null) {
            columnNames = dbutils.getColumnNames(rs);
        }

        while (rs.next()) {
            photo = (Photo) eop.newObject(DbConstants.PHOTO);
            for (int j = 0; j < columnNames.size(); j++) {
                photo.setValue((String) columnNames.elementAt(j),
                        (String) rs.getString((String) columnNames.elementAt(j)));
            }
            photosList.add(photo);
        }
        return photosList;
    } catch (Exception e) {
        logger.warn("Error occured while executing CarryonEntryIdQuery run query", e);
        throw new BaseDaoException("Error occured while executing CarryonEntryIdQuery run query " + sqlQuery,
                e);
    }
}

From source file:dao.PblogDateQuery.java

public HashSet run(Connection conn, String pblogid, String month, String year, String day) {

    //String sqlQuery = "select LEFT(entrydate,10) as entrydate from pblogtopics where pblogid='"+pblogid+"' and MONTH(entrydate)='"+month+"' and year(entrydate)='"+year+"'";
    String sqlQuery = "select LEFT(entrydate,10) as entrydate from pblogtopics where pblogid='" + pblogid
            + "' and MONTH(entrydate)='" + month + "' and year(entrydate)='" + year + "' and day(entrydate)='"
            + day + "'";
    logger.info("sqlQuery = " + sqlQuery);

    try {//from w ww. jav  a  2  s .  co m
        PreparedStatement stmt = conn.prepareStatement(sqlQuery);
        ResultSet rs = stmt.executeQuery();
        Vector columnNames = null;
        HashSet blogSet = new HashSet();
        Blog blog = null;

        if (rs != null) {
            columnNames = dbutils.getColumnNames(rs);
        }
        while (rs.next()) {
            blog = (Blog) eop.newObject(DbConstants.BLOG);
            for (int j = 0; j < columnNames.size(); j++) {
                blog.setValue((String) columnNames.elementAt(j),
                        (String) rs.getString((String) columnNames.elementAt(j)));
            }
            blogSet.add(blog);
        }
        return blogSet;
    } catch (Exception e) {
        logger.warn("Error occured while executing pblogdailyQuery run query", e);
        throw new BaseDaoException("Error occured while executing pblogdailyQuery run query " + sqlQuery, e);
    }
}

From source file:com.googlecode.datasourcetester.server.DataSourceTesterServiceImpl.java

public String[][] queryDataSource(String dataSourceJndiName, String query) {
    Connection conn = null;//from  w  w w.  jav  a  2  s .  c  o m
    try {
        InitialContext jndiContext = new InitialContext();
        DataSource ds = (DataSource) jndiContext.lookup(dataSourceJndiName);
        conn = ds.getConnection();
        PreparedStatement stmt = conn.prepareStatement(query);
        ResultSet rs = stmt.executeQuery();
        ResultSetMetaData resMeta = rs.getMetaData();
        LinkedList<String[]> rowList = new LinkedList<String[]>();
        String[] colLabels = new String[resMeta.getColumnCount()];
        for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) {
            colLabels[colNr - 1] = resMeta.getColumnName(colNr);
        }
        rowList.add(colLabels);
        while (rs.next()) {
            String[] rowData = new String[resMeta.getColumnCount()];
            for (int colNr = 1; colNr <= resMeta.getColumnCount(); colNr++) {
                rowData[colNr - 1] = rs.getString(colNr);
            }
            rowList.add(rowData);
        }
        conn.close();
        return rowList.toArray(new String[rowList.size()][]);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException sqlEx) {
            logger.error(sqlEx.getMessage(), sqlEx);
        }
        return null;
    }
}

From source file:ece356.UserDBAO.java

public static ArrayList<String> querySpecializationTypes() throws ClassNotFoundException, SQLException {
    Connection con = null;/*  w w  w  .  j  a  va 2 s  .c o  m*/
    PreparedStatement pstmt = null;
    try {
        con = getConnection();

        // Query for general doctor information
        String query = "select specTypeName from specializationType";
        pstmt = con.prepareStatement(query);

        ResultSet resultSet;
        resultSet = pstmt.executeQuery();

        ArrayList<String> specTypeList = new ArrayList<String>();
        while (resultSet.next()) {
            String user = resultSet.getString("specTypeName");
            specTypeList.add(user);
        }
        return specTypeList;
    } catch (Exception e) {
        System.out.println("EXCEPTION:%% " + e);
    } finally {
        if (pstmt != null) {
            pstmt.close();
        }
        if (con != null) {
            con.close();
        }
    }
    return null;
}

From source file:dao.CollModeratorsListQuery.java

/**
 * This method lists all the moderators for a collabrum
 * @param conn the connection/*from   w  w  w . j a  v a  2 s  . com*/
 * @param collabrumId the collabrumid
 * @return HashSet the set that has the list of moderators for these collabrums.
 * @throws BaseDaoException - when error occurs
 **/
public HashSet run(Connection conn, String collabrumId) throws BaseDaoException {

    String sqlQuery = "select distinct CONCAT(hd.fname,' ',hd.lname) AS membername, "
            + "hd.login, hd.loginid, c1.collabrumid, c2.name from colladmin c1, "
            + "hdlogin hd, collabrum c2 where c1.loginid=hd.loginid "
            + "and c1.collabrumid=c2.collabrumid and c1.collabrumid=" + collabrumId + "";
    try {
        PreparedStatement stmt = conn.prepareStatement(sqlQuery);
        ResultSet rs = stmt.executeQuery();
        Vector columnNames = null;
        Collabrum collabrum = null;
        HashSet pendingSet = new HashSet();

        if (rs != null) {
            columnNames = dbutils.getColumnNames(rs);
        }

        while (rs.next()) {
            collabrum = (Collabrum) eop.newObject("collabrum");
            for (int j = 0; j < columnNames.size(); j++) {
                collabrum.setValue((String) columnNames.elementAt(j),
                        (String) rs.getString((String) columnNames.elementAt(j)));
            }
            pendingSet.add(collabrum);
        }
        return pendingSet;
    } catch (Exception e) {
        throw new BaseDaoException(
                "Error occured while executing collabrum moderatorslist run query " + sqlQuery, e);
    }
}

From source file:mx.com.pixup.portal.dao.ArchivoBaseGenerateDaoJdbc.java

public void generateXML() {

    //querys/*from ww w  . j  av  a 2s  .  co  m*/
    String sql = "select * from LATABLA";

    try {
        //seccion de preparacion de la query
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        //seccion de nodo raiz

        while (resultSet.next()) {

            //aqu se hace la magia para el XML
        }

        //se genera el xml fsico
    } catch (Exception e) {
        //*** se quit el return porque el mtodo es void
        System.out.println(e.getMessage());
    }

}

From source file:uta.ak.TestNodejsInterface.java

private void testFromDB() throws Exception {

    Connection con = null; //MYSQL
    Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL
    con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL
    System.out.println("connection yes");

    System.out.println("query records...");
    String querySQL = "SELECT" + "   * " + "FROM " + "   c_rawtext " + "WHERE " + "tag like 'function%'";

    PreparedStatement preparedStmt = con.prepareStatement(querySQL);
    ResultSet rs = preparedStmt.executeQuery();

    Set<String> filterDupSet = new HashSet<>();

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 1);//from  w w w . ja v a2s. com
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    while (rs.next()) {

        System.out.println(rs.getString("title") + "  " + rs.getString("text") + "  " + rs.getString("tag"));

        String formattedDate = format1.format(new Date());

        String interfaceMsg = "<message> " + "    <title> " + rs.getString("title") + "    </title> "
                + "    <text> " + StringEscapeUtils.escapeXml10(rs.getString("text")) + "    </text> "
                + "    <textCreatetime> " + formattedDate + "    </textCreatetime> " + "    <tag> "
                + rs.getString("tag") + "    </tag> " + "</message>";

        //            String restUrl="http://192.168.0.103:8991/usttmp_textreceiver/rest/addText";
        String restUrl = "http://127.0.0.1:8991/usttmp_textreceiver/rest/addText";

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_XML);
        headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
        //            headers.setContentLength();
        HttpEntity<String> entity = new HttpEntity<String>(interfaceMsg, headers);

        ResponseEntity<String> result = restTemplate.exchange(restUrl, HttpMethod.POST, entity, String.class);

        System.out.println(result.getBody());

    }

}

From source file:com.l2jfree.gameserver.datatables.HennaTable.java

private void restoreHennaData() {
    Connection con = null;/* w w w. j av a  2 s. com*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(LOAD_HENNA);
        ResultSet hennadata = statement.executeQuery();
        fillHennaTable(hennadata);
        hennadata.close();
        statement.close();
    } catch (Exception e) {
        _log.error("error while creating henna table!", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}

From source file:com.wso2telco.dbUtil.DataBaseConnectUtils.java

/**
 * Get SP related configurations/*from w w w .  ja  v a  2 s  . co  m*/
 *
 * @param sessionId
 * @return
 * @throws ConfigurationException
 * @throws CommonAuthenticatorException
 */
public static BackChannelRequestDetails getRequestDetailsBySessionId(String sessionId)
        throws ConfigurationException, CommonAuthenticatorException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    BackChannelRequestDetails backchannelRequestDetails = null;
    ResultSet resultSet = null;

    String getUserDetailsQuery = "select * FROM backchannel_request_details where session_id=?";

    try {
        connection = getConnectDBConnection();

        if (log.isDebugEnabled()) {
            log.debug("Executing the query " + getUserDetailsQuery);
        }

        preparedStatement = connection.prepareStatement(getUserDetailsQuery);
        preparedStatement.setString(1, sessionId);
        resultSet = preparedStatement.executeQuery();

        if (resultSet.next()) {
            backchannelRequestDetails = new BackChannelRequestDetails();
            backchannelRequestDetails.setSessionId(resultSet.getString("session_id"));
            backchannelRequestDetails.setAuthCode(resultSet.getString("auth_code"));
            backchannelRequestDetails.setCorrelationId(resultSet.getString("correlation_id"));
            backchannelRequestDetails.setMsisdn(resultSet.getString("msisdn"));
            backchannelRequestDetails
                    .setNotificationBearerToken(resultSet.getString("notification_bearer_token"));
            backchannelRequestDetails.setNotificationUrl(resultSet.getString("notification_url"));
            backchannelRequestDetails.setClientId(resultSet.getString("client_id"));
        }
    } catch (SQLException e) {
        handleException("Error occurred while fetching SP related data for the Session Id: " + sessionId, e);
    } catch (NamingException e) {
        throw new ConfigurationException("DataSource could not be found in mobile-connect.xml");
    } finally {
        closeAllConnections(preparedStatement, connection, resultSet);
    }

    return backchannelRequestDetails;
}

From source file:com.wso2telco.dbUtil.DataBaseConnectUtils.java

/**
 * Get user details in Back Channeling Scenario using sessionID
 *
 * @param sessionId Id of the session//from   w w w .  j  a  v a  2s  .  co m
 */
public static BackChannelRequestDetails getBackChannelUserDetails(String sessionId)
        throws ConfigurationException, CommonAuthenticatorException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    BackChannelRequestDetails backChannelRequestDetails = null;
    ResultSet resultSet = null;

    String getUserDetailsQuery = "select * from backchannel_request_details where session_id=?";

    try {
        connection = getConnectDBConnection();

        if (log.isDebugEnabled()) {
            log.debug("Executing the query " + getUserDetailsQuery);
        }

        preparedStatement = connection.prepareStatement(getUserDetailsQuery);
        preparedStatement.setString(1, sessionId);
        resultSet = preparedStatement.executeQuery();

        if (resultSet.next()) {

            backChannelRequestDetails = new BackChannelRequestDetails();
            backChannelRequestDetails.setCorrelationId(resultSet.getString("correlation_id"));
            backChannelRequestDetails.setSessionId(resultSet.getString("session_id"));
            backChannelRequestDetails.setNotificationUrl(resultSet.getString("notification_url"));
            backChannelRequestDetails
                    .setNotificationBearerToken(resultSet.getString("notification_bearer_token"));
            backChannelRequestDetails.setAuthCode(resultSet.getString("auth_code"));
            backChannelRequestDetails.setMsisdn(resultSet.getString("msisdn"));
            backChannelRequestDetails.setRequestIniticatedTime(resultSet.getString("request_initiated_time"));
            backChannelRequestDetails.setClientId(resultSet.getString("client_id"));
            backChannelRequestDetails.setRedirectUrl(resultSet.getString("redirect_url"));
        }
    } catch (SQLException e) {
        handleException("Error occurred while getting user related details for session: " + sessionId
                + "in BackChannel " + "Scenario.", e);
    } catch (NamingException e) {
        throw new ConfigurationException("DataSource could not be found in mobile-connect.xml");
    } finally {
        closeAllConnections(preparedStatement, connection, resultSet);
    }

    return backChannelRequestDetails;
}