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:at.becast.youploader.account.Account.java

public static boolean exists(String name) {
    Connection c = SQLite.getInstance();
    Statement stmt;
    try {//from ww w  .j  a  va  2 s  . c  o m
        stmt = c.createStatement();
        String sql = "SELECT * FROM `accounts` WHERE `name`='" + name + "'";
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.isBeforeFirst()) {
            stmt.close();
            return true;
        } else {
            stmt.close();
            return false;
        }
    } catch (SQLException e) {
        LOG.error("Account exists error!", e);
        return false;
    }
}

From source file:com.hangum.tadpole.summary.report.DailySummaryReportJOB.java

/**
 * ? quote sql? ? .//from  ww w  .j av  a 2 s  .c  o  m
 * 
 * @param userDB
 * @param strDML
 * @param args
 */
public static String executSQL(UserDBDAO userDB, String strTitle, String strDML) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("execute query " + strDML);

    java.sql.Connection javaConn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        javaConn = client.getDataSource().getConnection();
        stmt = javaConn.createStatement();
        rs = stmt.executeQuery(strDML);

        return DailySummaryReport.makeResultSetTOHTML(strTitle, rs, 100);
    } finally {
        try {
            if (rs != null)
                rs.close();
        } catch (Exception e) {
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception e) {
        }
        try {
            if (javaConn != null)
                javaConn.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.aurel.track.admin.server.status.ServerStatusBL.java

/**
 * /*from   ww  w .  ja va  2 s . c o m*/
 */
public static Double loadPing() {
    //
    //
    //
    //
    Connection connection = null;
    try {
        connection = InitDatabase.getConnection();
        Date start = new Date();
        for (int i = 0; i < 10; ++i) {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT OBJECTID FROM TSITE");
            while (rs.next()) {
                rs.getInt(1);
            }
            rs.close();
            stmt.close();
        }
        Date stop = new Date();
        return new Double((stop.getTime() - start.getTime())) / 10.0;
    } catch (Exception e) {
        LOGGER.error("Can't ping: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOGGER.warn("Closing the connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
    return -999.99;
}

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

public static void getCoffeesBoughtBySupplier(String supplierName, Connection con) throws SQLException {
    Statement stmt = null;
    String query = "SELECT COFFEES.COF_NAME " + "FROM COFFEES, SUPPLIERS " + "WHERE SUPPLIERS.SUP_NAME LIKE '"
            + supplierName + "' " + "and SUPPLIERS.SUP_ID = COFFEES.SUP_ID";

    try {/*from  ww  w .  j  a v a 2s. c  o m*/
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        System.out.println("Coffees bought from " + supplierName + ": ");
        while (rs.next()) {
            String coffeeName = rs.getString(1);
            System.out.println("     " + coffeeName);
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:bizlogic.Records.java

public static void add(Connection DBcon, String sensor_name, String smpl_interval, String running, String name)
        throws SQLException {

    String isRunning;/*from w ww  .jav  a  2  s.  co  m*/
    Statement st;
    ResultSet rs = null;

    try {
        st = DBcon.createStatement();
        rs = st.executeQuery("SELECT * FROM USERCONF.SENSORLIST WHERE NAME = '" + sensor_name + "' ");

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Records.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    }
    rs.next();
    int id = rs.getInt("sensor_id");

    String sql_statement;
    if (running.equals("true")) {
        isRunning = "B'1'";
    } else {
        isRunning = "B'0'";
    }

    st = DBcon.createStatement();
    sql_statement = "INSERT INTO USERCONF.LOG_LIST(SENSOR_ID, SMPL_INTERVAL, RUNNING, NAME) " + "VALUES (" + id
            + ", " + smpl_interval + ", " + isRunning + ", " + "'" + name + "'" + " );";
    System.out.println(sql_statement);
    st.clearBatch();
    st = DBcon.createStatement();
    DBcon.createStatement();
    st.executeUpdate(sql_statement);

}

From source file:com.cloudera.sqoop.manager.CubridManagerExportTest.java

public static void assertRowCount(long expected, String tableName, Connection connection) {
    Statement stmt = null;
    ResultSet rs = null;/*  ww  w. j  av a  2s. c o m*/
    try {
        stmt = connection.createStatement();
        rs = stmt.executeQuery("SELECT count(*) FROM " + tableName);
        rs.next();
        assertEquals(expected, rs.getLong(1));
    } catch (SQLException e) {
        LOG.error("Can't verify number of rows", e);
        fail();
    } finally {
        try {
            connection.commit();
            if (stmt != null) {
                stmt.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException ex) {
            LOG.info("Ignored exception in finally block.");
        }
    }
}

From source file:com.uber.hoodie.cli.utils.HiveUtil.java

private static long countRecords(String jdbcUrl, HoodieTableMetaClient source, String srcDb,
        String startDateStr, String endDateStr, String user, String pass) throws SQLException {
    Connection conn = HiveUtil.getConnection(jdbcUrl, user, pass);
    ResultSet rs = null;//from   w w  w  . ja va2  s  .  c o m
    Statement stmt = conn.createStatement();
    try {
        //stmt.execute("set mapred.job.queue.name=<queue_name>");
        stmt.execute("set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat");
        stmt.execute("set hive.stats.autogather=false");
        rs = stmt.executeQuery("select count(`_hoodie_commit_time`) as cnt from " + srcDb + "."
                + source.getTableConfig().getTableName() + " where datestr>'" + startDateStr
                + "' and datestr<='" + endDateStr + "'");
        if (rs.next()) {
            return rs.getLong("cnt");
        }
        return -1;
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:com.uber.hoodie.cli.utils.HiveUtil.java

public static long countRecords(String jdbcUrl, HoodieTableMetaClient source, String dbName, String user,
        String pass) throws SQLException {
    Connection conn = HiveUtil.getConnection(jdbcUrl, user, pass);
    ResultSet rs = null;/* w w  w. j  a v a 2 s. c  o  m*/
    Statement stmt = conn.createStatement();
    try {
        //stmt.execute("set mapred.job.queue.name=<queue_name>");
        stmt.execute("set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat");
        stmt.execute("set hive.stats.autogather=false");
        rs = stmt.executeQuery("select count(`_hoodie_commit_time`) as cnt from " + dbName + "."
                + source.getTableConfig().getTableName());
        long count = -1;
        if (rs.next()) {
            count = rs.getLong("cnt");
        }
        System.out.println("Total records in " + source.getTableConfig().getTableName() + " is " + count);
        return count;
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:com.hp.test.framework.generatejellytess.GenerateJellyTests.java

public static void exemappingmodel() {
    boolean clean_files = false;

    Map<Integer, String> Master_ModelList = new HashMap<Integer, String>();

    try {/*from   w ww.j  av  a  2 s  . c o m*/
        Class.forName("org.sqlite.JDBC");

        log.info("TestCase DB Location" + mp.getProperty("MODEL_DB_LOCATION"));
        alm_test_location = mp.getProperty("ALM_FORMAT_STORE_LOC");
        Jelly_Tests_location = mp.getProperty("JELLY_TESTS_LOCATION");
        CLEAN_JELLY_TESTS = mp.getProperty("CLEAN_JELLY_TESTS");

        if (CLEAN_JELLY_TESTS.toLowerCase().equals("yes")) {
            clean_files = true;
        }
        connection = DriverManager.getConnection("jdbc:sqlite:" + mp.getProperty("MODEL_DB_LOCATION"));
        //  int GID_int = Integer.parseInt(GID);

        Statement Master_statement = connection.createStatement();
        ResultSet rs_master = Master_statement.executeQuery(
                "SELECT GID,FEATURENAME FROM DM_MASTERMODELXML_REF WHERE TESTCASE_GEN_STATUS LIKE 'COMPLETED' AND JELLYCASE_GEN_STATUS IS NULL  ORDER BY GID");

        while (rs_master.next()) {
            Master_ModelList.put(rs_master.getInt("GID"), rs_master.getString("FEATURENAME"));

        }
        rs_master = null;
        Master_statement = null;
        // connection.close();
    } catch (SQLException e) {

        log.error("Error in getting data from DM_MASTERMODELXML_REF table to generate Jelly and ALM TESTS");

    } catch (ClassNotFoundException e) {
        log.error("Exception in exemapping model function" + e.getMessage());
    }

    if (Master_ModelList.isEmpty()) {
        log.info(
                "********************************************************************************************************************************************");
        log.info(
                "Jelly Testcases are already generated for all the Models; Please check the column status \"JELLYCASE_GEN_STATUS\" in \"DM_MASTERMODELXML_REF\"");
        log.info(
                "********************************************************************************************************************************************");
        throw new RuntimeException("Runtime Exception");
        //  System.exit(0);
    }

    for (int key : Master_ModelList.keySet()) {
        GenerateJellyTests.CreateJellyTestsFolder(Jelly_Tests_location, clean_files, Master_ModelList.get(key));
        temp_jelly_Tests_location = Jelly_Tests_location + Master_ModelList.get(key);
        glb_Feature_Name = Master_ModelList.get(key);
        log.info("Started generating Jelly Tests for the Feature::" + glb_Feature_Name);
        log.info("***************************************************");
        genjellyTests(String.valueOf(key), Master_ModelList.get(key));
        try {
            DatabaseUtils.UpdateSingleValue("DM_MASTERMODELXML_REF", "COMPLETED", "JELLYCASE_GEN_STATUS", "GID",
                    String.valueOf(key));
        } catch (ClassNotFoundException e) {
            log.error("Exception in updating DM_MASTERMODELXML_REF table" + e.getMessage());
        }
        log.info("End of generating Jelly Tests for the Feature::" + glb_Feature_Name);

    }

}

From source file:com.l2jfree.gameserver.util.TableOptimizer.java

public static void optimize() {
    Connection con = null;/*  w  w w .j av a 2s  . c  om*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        Statement st = con.createStatement();

        final ArrayList<String> tables = new ArrayList<String>();
        {
            ResultSet rs = st.executeQuery("SHOW FULL TABLES");
            while (rs.next()) {
                String tableType = rs.getString(2/*"Table_type"*/);

                if (tableType.equals("VIEW"))
                    continue;

                tables.add(rs.getString(1));
            }
            rs.close();
        }

        {
            ResultSet rs = st.executeQuery("CHECK TABLE " + StringUtils.join(tables, ","));
            while (rs.next()) {
                String table = rs.getString("Table");
                String msgType = rs.getString("Msg_type");
                String msgText = rs.getString("Msg_text");

                if (msgType.equals("status"))
                    if (msgText.equals("OK"))
                        continue;

                _log.warn("TableOptimizer: CHECK TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            rs.close();

            _log.info("TableOptimizer: Database tables have been checked.");
        }

        {
            ResultSet rs = st.executeQuery("ANALYZE TABLE " + StringUtils.join(tables, ","));
            while (rs.next()) {
                String table = rs.getString("Table");
                String msgType = rs.getString("Msg_type");
                String msgText = rs.getString("Msg_text");

                if (msgType.equals("status"))
                    if (msgText.equals("OK") || msgText.equals("Table is already up to date"))
                        continue;

                _log.warn("TableOptimizer: ANALYZE TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            rs.close();

            _log.info("TableOptimizer: Database tables have been analyzed.");
        }

        {
            ResultSet rs = st.executeQuery("OPTIMIZE TABLE " + StringUtils.join(tables, ","));
            while (rs.next()) {
                String table = rs.getString("Table");
                String msgType = rs.getString("Msg_type");
                String msgText = rs.getString("Msg_text");

                if (msgType.equals("status"))
                    if (msgText.equals("OK") || msgText.equals("Table is already up to date"))
                        continue;

                if (msgType.equals("note"))
                    if (msgText.equals("Table does not support optimize, doing recreate + analyze instead"))
                        continue;

                _log.warn("TableOptimizer: OPTIMIZE TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            rs.close();

            _log.info("TableOptimizer: Database tables have been optimized.");
        }
        st.close();
    } catch (Exception e) {
        _log.warn("TableOptimizer: Cannot optimize database tables!", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}