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:com.trackplus.ddl.DataReader.java

private static int getBlobTableData(BufferedWriter writer, Connection connection) throws DDLException {
    try {//  ww w  .  j  a v  a2 s  .c o m
        Statement st = connection.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM TBLOB");
        int idx = 0;
        while (rs.next()) {
            StringBuilder line = new StringBuilder();

            //OBJECTID
            String value = rs.getString("OBJECTID");
            line.append(value).append(",");

            //BLOBVALUE
            Blob blobValue = rs.getBlob("BLOBVALUE");
            if (blobValue != null) {
                String str = new String(Base64.encodeBase64(blobValue.getBytes(1l, (int) blobValue.length())));
                if (str.length() == 0) {
                    str = " ";
                }
                line.append(str);
            } else {
                line.append("null");
            }
            line.append(",");

            //TPUUID
            value = rs.getString("TPUUID");
            line.append(value);
            writer.write(line.toString());
            writer.newLine();
            idx++;
        }
        rs.close();
        return idx;
    } catch (SQLException ex) {
        throw new DDLException(ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new DDLException(ex.getMessage(), ex);
    }
}

From source file:com.ery.hadoop.mrddx.hive.HiveOutputFormat.java

/**
 * ddlHQL?//  w  ww .j a  v a 2 s. c  o m
 * 
 * @param hiveConf hive?
 * @throws SQLException
 */
public static void executeDDLHQL(HiveConfiguration hiveConf) throws SQLException {
    String ddls = hiveConf.getOutputHiveExecuteDDLHQL();
    if (null == ddls || ddls.trim().length() <= 0) {
        return;
    }
    String ddl[] = ddls.split(";");
    Connection conn = null;
    try {
        conn = hiveConf.getOutputConnection();
    } catch (ClassNotFoundException e) {
        MRLog.error(LOG, "create hive conn error!");
        e.printStackTrace();
    }

    Statement stat = conn.createStatement();
    for (int i = 0; i < ddl.length; i++) {
        try {
            stat.executeQuery(ddl[i]);
        } catch (Exception e) {
            MRLog.errorException(LOG, "execute ddl error, hql:" + ddl[i], e);
        }
    }

    // 
    close(conn);
}

From source file:com.trackplus.ddl.DataReader.java

private static int getClobTableData(BufferedWriter writer, Connection connection) throws DDLException {
    Statement st = MetaDataBL.createStatement(connection);
    try {//from   w w w .  j av  a  2  s .  c o  m
        ResultSet rs = st.executeQuery("SELECT * FROM TMSPROJECTEXCHANGE");
        int idx = 0;
        String[] columns = MetaDataBL.getColumnsMsProjectExchange();
        while (rs.next()) {
            StringBuilder line = new StringBuilder();
            for (int i = 0; i < columns.length; i++) {
                String value = rs.getString(columns[i]);
                if (value != null && "FILECONTENT".equals(columns[i])) {
                    value = encodeBase64FileContent(value);
                }
                line.append(value);
                if (i < columns.length - 1) {
                    line.append(",");
                }
            }
            MetaDataBL.appendLine(writer, line.toString());
            idx++;
        }
        rs.close();
        return idx;
    } catch (SQLException ex) {
        throw new DDLException(ex.getMessage(), ex);
    }
}

From source file:net.antidot.sql.model.core.SQLConnector.java

/**
 * Get time zone stored in MySQL database. Reference :
 * http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html The result
 * can be NULL if the Timezone can't be determinated.
 * //from   w  w  w  .  j a va  2s  .com
 * The appropriated timezone returned follow these priorities : 1) If
 * 
 * @param conn
 * @return
 * @throws SQLException
 */
public static String getTimeZone(Connection conn) throws SQLException {
    if (log.isDebugEnabled())
        log.debug("[SQLConnector:getTimeZone]");
    Statement stmt = conn.createStatement();
    String query = "SELECT @@global.time_zone, @@session.time_zone;";
    ResultSet rs = stmt.executeQuery(query);

    while (rs.next()) {
        // The global time_zone system variable indicates
        // the time zone the server currently is operating in.
        String globalMySQLTimeZone = rs.getString("@@global.time_zone");
        // Initially, the session variable takes its value from the global
        // time_zone variable, but the client can change its own time zone.
        String sessionMySQLTimeZone = rs.getString("@@session.time_zone");
        String mySQLTimeZone = globalMySQLTimeZone;
        if (!globalMySQLTimeZone.equals(sessionMySQLTimeZone)) {
            // Use session time zone in priority
            mySQLTimeZone = sessionMySQLTimeZone;
        }
        if (log.isDebugEnabled())
            log.debug("[SQLConnector:getTimeZone] mySQLTimeZone extracted = " + mySQLTimeZone);
        return getTimeZoneFromMySQLFormat(mySQLTimeZone);
    }
    if (log.isWarnEnabled())
        log.warn(
                "[SQLConnector:getTimeZone] Impossible to read timezone from database. Timezone of current system selected.");
    return timeZoneToStr(TimeZone.getTimeZone("UTC"));
}

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

public static void checkSQLBinaryTableContent(String[] expected, String tableName, Connection connection) {
    Statement stmt = null;
    ResultSet rs = null;/*w  ww. ja  v  a  2  s . c o m*/
    try {
        stmt = connection.createStatement();
        rs = stmt.executeQuery("SELECT TOP 1 [b1], [b2] FROM " + tableName);
        rs.next();
        assertEquals(expected[0], rs.getString("b1"));
        assertEquals(expected[1], rs.getString("b2"));
    } catch (SQLException e) {
        LOG.error("Can't verify table content", 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:ca.sqlpower.persistance.CatNap.java

public static void load(Connection con, String tableName, Object loadTo, String where)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException {
    BeanUtils.describe(loadTo);//  w w  w. j av  a2 s .c o m
    Statement stmt = null;
    StringBuffer sql = new StringBuffer();
    try {
        sql.append("SELECT * FROM " + tableName + " WHERE " + where);
        sql.append("\n");

        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql.toString());
        while (rs.next()) {
            ResultSetMetaData metaData = rs.getMetaData();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                String beanPropertyName = underscoreToCamelCaps(metaData.getColumnName(i).toLowerCase());

                BeanUtils.setProperty(loadTo, beanPropertyName, rs.getObject(i));

            }
        }
    } catch (SQLException ex) {
        System.err.println("Catnap: Insert failed. Statement was:\n" + sql);
        throw ex;
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException ex) {
            System.err.println(
                    "Catnap: Couldn't close the statement.  Damn.  But at least you won a stack trace:");
            ex.printStackTrace();
        }
    }
}

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

public static void showSuppliers(ResultSet[] rs) throws SQLException {
    Connection con = DriverManager.getConnection("jdbc:default:connection");
    Statement stmt = null;
    String query = "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " + "from SUPPLIERS, COFFEES "
            + "where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " + "order by SUP_NAME";
    stmt = con.createStatement();//w ww .j  a v  a 2  s.  c o  m
    rs[0] = stmt.executeQuery(query);
}

From source file:jp.co.acroquest.endosnipe.data.dao.AbstractDao.java

/**
 * ?????????<br />/*w w w  . jav a  2s .co m*/
 *
 * @param database ??
 * @param sequenceName ??
 * @return ???????????????? <code>-1</code>
 * @throws SQLException SQL ?????
 */
protected static int createValueFromSequenceId(final String database, final String sequenceName)
        throws SQLException {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    int newMeasurementItemId = -1;
    try {
        conn = getConnection(database);
        stmt = conn.createStatement();
        String sql = ConnectionManager.getInstance().getSequenceSql(sequenceName);
        rs = stmt.executeQuery(sql);
        if (rs.next() == true) {
            newMeasurementItemId = rs.getInt(1);
        }
    } finally {
        SQLUtil.closeResultSet(rs);
        SQLUtil.closeStatement(stmt);
        SQLUtil.closeConnection(conn);
    }
    return newMeasurementItemId;
}

From source file:module.entities.NameFinder.DB.java

public static ArrayList<Integer> getConsultationIds() throws SQLException {
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT id FROM consultation;");
    ArrayList<Integer> ids = new ArrayList<>();
    while (rs.next()) {
        ids.add(rs.getInt(1));//w w w . ja  v a 2 s  . co m
    }
    return ids;
}

From source file:module.entities.NameFinder.DB.java

/**
 * /* www  .j a  v  a 2 s . c o  m*/
 *
 * @return
 * @throws java.sql.SQLException
 */
public static TreeMap<Integer, String> GetAnnotatedData() throws SQLException {
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM assignmentsdone;");
    TreeMap<Integer, String> dbJsonString = new TreeMap<>();
    //        ArrayList<String> dbJsonString = new ArrayList<>();
    while (rs.next()) {
        int json_id = rs.getInt("text_id");
        String json = rs.getString("json_out");
        dbJsonString.put(json_id, json);
    }
    return dbJsonString;
}