Example usage for java.sql Statement executeQuery

List of usage examples for java.sql Statement executeQuery

Introduction

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

Prototype

ResultSet executeQuery(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which returns a single ResultSet object.

Usage

From source file:TestDB.java

 /**
 * Runs a test by creating a table, adding a value, showing the table contents, and removing the
 * table.//from  w  w w .j  a  v a 2s  .  co  m
 */
public static void runTest() throws SQLException, IOException
{
   Connection conn = getConnection();
   try
   {
      Statement stat = conn.createStatement();

      stat.executeUpdate("CREATE TABLE Greetings (Message CHAR(20))");
      stat.executeUpdate("INSERT INTO Greetings VALUES ('Hello, World!')");

      ResultSet result = stat.executeQuery("SELECT * FROM Greetings");
      if (result.next())
         System.out.println(result.getString(1));
      result.close();
      stat.executeUpdate("DROP TABLE Greetings");
   }
   finally
   {
      conn.close();
   }
}

From source file:com.oracle.tutorial.jdbc.FilteredRowSetSample.java

public static void viewTable(Connection con) throws SQLException {
    Statement stmt = null;
    String query = "select * from COFFEE_HOUSES";
    try {/*from  w  ww  . j a  v a  2s . co m*/
        stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            System.out.println(rs.getInt("STORE_ID") + ", " + rs.getString("CITY") + ", " + rs.getInt("COFFEE")
                    + ", " + rs.getInt("MERCH") + ", " + rs.getInt("TOTAL"));
        }

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:Main.java

public static String QueryVcTable2(Statement stmt, String app_name) {
    String sql_1 = "SELECT app_versioncode FROM app_info.`msp_table_8.12_copy` WHERE app_name='" + app_name
            + "'";
    ResultSet result = null;//from   ww w  .  j  a va  2  s . co  m
    String v = null;
    try {
        result = stmt.executeQuery(sql_1);
        while (result.next()) {
            v = result.getString(1);
        }
        if (v != null)
            return v;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.nokia.helium.metadata.DerbyFactoryManagerCreator.java

/**
 * Checks the database integrity.//from   w  w  w .ja v  a  2  s  .co m
 * @param urlPath - database path to be connected to.
 * @return boolean - true if db is valid false otherwise.
 */
private static boolean checkDatabaseIntegrity(File database) throws MetadataException {
    boolean result = false;
    Connection connection = null;
    try {
        connection = DriverManager.getConnection("jdbc:derby:" + database);
        if (connection != null) {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("select version from version");
            int version = -1;
            if (rs.next()) {
                version = rs.getInt(1);
            }
            rs.close();
            stmt.close();
            connection.close();
            connection = null;
            result = version == Version.DB_VERSION;
        }
    } catch (SQLException ex) {
        try {
            DriverManager.getConnection("jdbc:derby:;shutdown=true");
        } catch (java.sql.SQLException sex) {
            // normal exception during database shutdown
            connection = null;
        }
        return false;
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (java.sql.SQLException sex) {
            // normal exception during database shutdown
            connection = null;
        }
        connection = null;
        if (!result) {
            try {
                DriverManager.getConnection("jdbc:derby:;shutdown=true");
            } catch (java.sql.SQLException sex) {
                // normal exception during database shutdown
                connection = null;
            }
        }
    }
    //shutdown unloads the driver, driver need to be loaded again.
    return result;
}

From source file:net.tirasa.ilgrosso.resetdb.Main.java

private static void resetOracle(final Connection conn) throws Exception {

    final Statement statement = conn.createStatement();

    ResultSet resultSet = statement.executeQuery(
            "SELECT 'DROP VIEW ' || object_name || ';'" + " FROM user_objects WHERE object_type='VIEW'");
    final List<String> drops = new ArrayList<String>();
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }//from w ww . ja v  a 2s  .c  o m
    resultSet.close();

    for (String drop : drops) {
        statement.executeUpdate(drop.substring(0, drop.length() - 1));
    }
    drops.clear();

    resultSet = statement.executeQuery("SELECT 'DROP INDEX ' || object_name || ';'"
            + " FROM user_objects WHERE object_type='INDEX'" + " AND object_name NOT LIKE 'SYS_%'");
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }
    resultSet.close();

    for (String drop : drops) {
        try {
            statement.executeUpdate(drop.substring(0, drop.length() - 1));
        } catch (SQLException e) {
            LOG.error("Could not perform: {}", drop);
        }
    }
    drops.clear();

    resultSet = statement.executeQuery("SELECT 'DROP TABLE ' || table_name || ' CASCADE CONSTRAINTS;'"
            + " FROM all_TABLES WHERE owner='" + ((String) ctx.getBean("username")).toUpperCase() + "'");
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }
    resultSet.close();

    resultSet = statement
            .executeQuery("SELECT 'DROP SEQUENCE ' || sequence_name || ';'" + " FROM user_SEQUENCES");
    while (resultSet.next()) {
        drops.add(resultSet.getString(1));
    }
    resultSet.close();

    for (String drop : drops) {
        statement.executeUpdate(drop.substring(0, drop.length() - 1));
    }

    statement.close();
    conn.close();
}

From source file:com.l2jfree.sql.L2DatabaseInstaller.java

private static double getDatabaseRevision() {
    double revision = -1;

    Connection con = null;/*  w  ww .java2 s .  c o  m*/
    try {
        con = L2Database.getConnection();

        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("SELECT revision FROM _revision ORDER BY revision DESC LIMIT 1");

        if (rs.next())
            revision = rs.getDouble(1);

        rs.close();
        st.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        L2Database.close(con);
    }

    return revision;
}

From source file:com.espertech.esperio.db.SupportDatabaseService.java

public static Object[][] readAll(String tableName) throws SQLException {
    Connection connection = getConnection(PARTURL, DBUSER, DBPWD);
    connection.setAutoCommit(true);//from www.ja v a  2 s . co  m
    Statement stmt = connection.createStatement();
    String sql = "select * from " + tableName;
    log.info("Executing sql : " + sql);
    ResultSet resultSet = stmt.executeQuery(sql);

    List<Object[]> rows = new ArrayList<Object[]>();
    while (resultSet.next()) {
        List<Object> row = new ArrayList<Object>();
        for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
            row.add(resultSet.getObject(i + 1));
        }
        rows.add(row.toArray());
    }

    Object[][] arr = new Object[rows.size()][];
    for (int i = 0; i < rows.size(); i++) {
        arr[i] = rows.get(i);
    }

    stmt.close();
    connection.close();
    return arr;
}

From source file:massbank.svn.SVNUtils.java

/**
 *
 *//*w  w  w  . j  a  va 2 s .  co  m*/
public static boolean checkDBExists(String dbName) {
    if (dbName.equals("")) {
        return false;
    }
    Connection con = connectDB(dbName);
    if (con == null) {
        return false;
    }
    try {
        Statement stmt = con.createStatement();
        String sql = "SHOW TABLES LIKE 'SPECTRUM'";
        ResultSet rs = stmt.executeQuery(sql);
        String val = "";
        if (rs.first()) {
            val = rs.getString(1);
        }
        con.close();
        if (!val.equals("")) {
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:au.org.ala.layers.stats.ObjectsStatsGenerator.java

private static void updateBbox() {

    try {/*from www. j  a v  a 2  s .  c  o  m*/
        Connection conn = getConnection();
        String sql = "SELECT pid from objects where bbox is null limit 200000;";
        logger.info("loading bbox ...");
        Statement s1 = conn.createStatement();
        ResultSet rs1 = s1.executeQuery(sql);

        LinkedBlockingQueue<String[]> data = new LinkedBlockingQueue<String[]>();
        while (rs1.next()) {
            data.put(new String[] { rs1.getString("pid") });
        }

        CountDownLatch cdl = new CountDownLatch(data.size());

        BboxThread[] threads = new BboxThread[CONCURRENT_THREADS];
        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j] = new BboxThread(data, cdl, getConnection().createStatement());
            threads[j].start();
        }

        cdl.await();

        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j].s.close();
            threads[j].interrupt();
        }
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return;
}

From source file:com.amazon.services.awsrum.utils.RedshiftUtils.java

/**
 * Helper method to determine if a table exists in the Redshift database
 * /*w  w  w .ja v a  2  s . c o  m*/
 * @param loginProperties
 *            A properties file containing the authentication credentials for the database
 * @param redshiftURL
 *            The JDBC URL of the Redshift database
 * @param tableName
 *            The table to check existence of
 * @return true if connection to the database is successful and the table exists, otherwise
 *         false
 */
public static boolean tableExists(Properties loginProperties, String redshiftURL, String tableName) {
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(redshiftURL, loginProperties);

        Statement stmt = conn.createStatement();
        stmt.executeQuery("SELECT * FROM " + tableName + " LIMIT 1;");
        stmt.close();
        conn.close();
        return true;
    } catch (SQLException e) {
        LOG.error(e);
        try {
            conn.close();
        } catch (Exception e1) {
        }
        return false;
    }
}