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:net.sf.jdbcwrappers.trim.TrimmingTest.java

@Test
public void testPreparedStatement() throws SQLException {
    PreparedStatement statement = connection.prepareStatement("SELECT * FROM TEST WHERE INT_COL=?");
    try {/*from   w  w w  .j a  v  a 2  s.c o m*/
        statement.setInt(1, 12);
        ResultSet rs = statement.executeQuery();
        rs.next();
        assertEquals("test", rs.getString(2));
        assertEquals("test", rs.getString("CHAR_COL"));
    } finally {
        statement.close();
    }
}

From source file:com.product.Product.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *//*from w  w  w  .j a  va  2s .  com*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts() throws SQLException {
    if (connect == null) {
        return "not connected";
    } else {
        String query = "Select * from products";
        PreparedStatement prepstmnt = connect.prepareStatement(query);
        ResultSet rs = prepstmnt.executeQuery();
        String result = "";
        JSONArray productArr = new JSONArray();
        while (rs.next()) {
            Map productMap = new LinkedHashMap();
            productMap.put("productID", rs.getInt("product_id"));
            productMap.put("name", rs.getString("name"));
            productMap.put("description", rs.getString("description"));
            productMap.put("quantity", rs.getInt("quantity"));
            productArr.add(productMap);
        }
        result = productArr.toString();
        return result.replace("},", "},\n");
    }

}

From source file:de.ingrid.iplug.dsc.index.producer.PlugDescriptionConfiguredDatabaseRecordSetProducer.java

private void createRecordIdsFromDatabase() {
    try {//w w  w . j a  v  a 2 s . c o m
        List<String> recordIds = new ArrayList<String>();
        if (log.isDebugEnabled()) {
            log.debug("SQL: " + recordSql);
        }
        PreparedStatement ps = connection.prepareStatement(recordSql);
        try {
            ResultSet rs = ps.executeQuery();
            try {
                while (rs.next()) {
                    recordIds.add(rs.getString(1));
                }
                recordIdIterator = recordIds.listIterator();
                numRecords = recordIds.size();
            } catch (Exception e) {
                throw e;
            } finally {
                rs.close();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            ps.close();
        }
    } catch (Exception e) {
        log.error("Error creating record ids.", e);
    }
}

From source file:com.assignment4.productdetails.java

/**
 * Retrieves representation of an instance of com.oracle.products.ProductResource
 * @return an instance of java.lang.String
 *//* w w  w  .  j  a v a  2  s  .  c  o  m*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getAllProducts() throws SQLException {
    if (conn == null) {
        return "it is not connected";
    } else {
        String query = "Select * from products";
        PreparedStatement pstmt = conn.prepareStatement(query);
        ResultSet res = pstmt.executeQuery();
        String results = "";
        JsonArrayBuilder podtAr = Json.createArrayBuilder();
        while (res.next()) {
            // Map pdtmap = new LinkedHashMap();
            JsonObjectBuilder obj = Json.createObjectBuilder();//using json object for using json api
            obj.add("productID", res.getInt("product_id"));
            obj.add("name", res.getString("name"));
            obj.add("description", res.getString("description"));
            obj.add("quantity", res.getInt("quantity"));
            podtAr.add(obj);
        }
        results = podtAr.build().toString();
        return results.replace("},", "},\n");
    }

}

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

private CharNameTable() {
    Connection con = null;/*from w  w w .ja va  2 s .c om*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection();

        PreparedStatement statement = con
                .prepareStatement("SELECT charId, account_name, char_name FROM characters");
        ResultSet rset = statement.executeQuery();

        while (rset.next())
            update(rset.getInt("charId"), rset.getString("account_name"), rset.getString("char_name"));

        rset.close();
        statement.close();
    } catch (SQLException e) {
        _log.warn("", e);
    } finally {
        L2DatabaseFactory.close(con);
    }

    _log.info("CharNameTable: Loaded " + _mapByObjectId.size() + " character names.");
}

From source file:com.uit.anonymousidentity.Repository.Nonces.NonceJDBCTemplate.java

@Override
public Nonce find(BigInteger i) throws SQLException {
    String sql = "select * from " + TABLE_NAME + " where " + VALUE + " = ?";
    PreparedStatement pst = dataSource.getConnection().prepareStatement(sql);
    Nonce n = new Nonce();
    pst.setBytes(1, i.toByteArray());//w  w  w.  jav a  2  s . c  om
    ResultSet rs = pst.executeQuery();
    if (rs.next()) {
        n.setIssuerSid(rs.getString(SID));
        n.setByteArray(rs.getBytes(VALUE));
        n.setId(rs.getInt(ID));
        return n;
    } else
        return null;
}

From source file:com.artivisi.iso8583.persistence.MapperServiceTestIT.java

private void verifyCountDataelement(Mapper m, Connection conn, int count) throws SQLException {
    String sqlSelectDataelement = "select count(*) from iso8583_dataelement where id_mapper = ?";
    PreparedStatement psSelectDataelement = conn.prepareStatement(sqlSelectDataelement);
    psSelectDataelement.setString(1, m.getId());
    ResultSet rsSelectDataelement = psSelectDataelement.executeQuery();
    assertTrue(rsSelectDataelement.next());
    assertEquals(new Integer(count), new Integer(rsSelectDataelement.getInt(1)));
}

From source file:com.alibaba.druid.benckmark.pool.CaseKylin_mysql.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();/* w  ww .  j  a  v a 2  s  . c om*/

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        PreparedStatement stmt = conn.prepareStatement("SELECT 1 FROM DUAL");
                        ResultSet rs = stmt.executeQuery();
                        rs.next();
                        rs.getInt(1);
                        rs.close();
                        stmt.close();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}

From source file:com.vertica.hivestoragehandler.VerticaRecordWriter.java

public VerticaRecordWriter(Connection conn, String writerTable, long batch) throws SQLException {
    this.connection = conn;
    batchSize = batch;//from   w ww . ja v a  2  s .  c  o  m

    vTable = new VerticaRelation(writerTable);

    StringBuilder sb = new StringBuilder();
    sb.append("INSERT INTO ");
    sb.append(vTable.getQualifiedName());

    StringBuilder values = new StringBuilder();
    values.append(" VALUES(");
    sb.append("(");

    String metaStmt = "select ordinal_position, column_name, data_type, is_identity, data_type_name "
            + "from v_catalog.odbc_columns " + "where schema_name = ? and table_name = ? "
            + "order by ordinal_position;";

    PreparedStatement stmt = conn.prepareStatement(metaStmt);
    stmt.setString(1, vTable.getSchema());
    stmt.setString(2, vTable.getTable());

    ResultSet rs = stmt.executeQuery();
    boolean addComma = false;
    while (rs.next()) {
        if (!rs.getBoolean(4)) {
            if (addComma) {
                sb.append(',');
                values.append(',');
            }
            sb.append(rs.getString(2));
            values.append('?');
            addComma = true;
        } else {
            LOG.debug("Skipping identity column " + rs.getString(4));
        }
    }

    sb.append(')');
    values.append(')');
    sb.append(values.toString());

    statement = conn.prepareStatement(sb.toString());
}

From source file:io.muic.ooc.webapp.service.UserService.java

public boolean userExist(Connection conn, String id) {

    if (id == null) {
        return false;
    }/*from w  ww. ja  v  a 2  s.co m*/

    String query = "SELECT * from account WHERE id = ?";
    try {
        PreparedStatement preparedStatement = conn.prepareStatement(query);
        preparedStatement.setString(1, id);

        // do update
        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            System.out.println("User Exist function");
            if (resultSet.getString("id").equals(id)) {
                return true;
            }
        }
        return false;
    } catch (SQLException e) {
        System.out.println("Can't check");
    }
    return false;
}