Example usage for java.sql ResultSet getString

List of usage examples for java.sql ResultSet getString

Introduction

In this page you can find the example usage for java.sql ResultSet getString.

Prototype

String getString(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    Connection con = null;//ww w .ja v  a2 s.c om
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con = DriverManager.getConnection("jdbc:oracle:thin:@192.201.32.92:1521:psprd1", "username", "password");
    String query = null;
    ResultSet rset = null;
    query = "UPDATE t1 " + " SET id = ?";
    PreparedStatement stmt = con.prepareStatement(query);
    // stmt.setInt(paramIndex++, null);
    stmt.setNull(1, java.sql.Types.INTEGER);
    stmt.executeUpdate();
    stmt.close();
    query = "select id from t1 ";
    stmt = con.prepareStatement(query);
    rset = stmt.executeQuery();
    rset.next();
    System.out.println(rset.getString("id"));
    rset.close();
    stmt.close();
    con.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    //    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet privileges = null;
    DatabaseMetaData meta = conn.getMetaData();
    // The '_' character represents any single character.
    // The '%' character represents any sequence of zero
    // or more characters.
    privileges = meta.getColumnPrivileges(conn.getCatalog(), null, "survey", "%");
    while (privileges.next()) {

        String catalog = privileges.getString("TABLE_CAT");
        String schema = privileges.getString("TABLE_SCHEM");
        String tableName = privileges.getString("TABLE_NAME");
        String dbColumn = privileges.getString("COLUMN_NAME");
        String privilege = privileges.getString("PRIVILEGE");
        String grantor = privileges.getString("GRANTOR");
        String grantee = privileges.getString("GRANTEE");
        String isGrantable = privileges.getString("IS_GRANTABLE");

        System.out.println("table name:" + tableName);
        System.out.println("catalog:" + catalog);
        System.out.println("column:" + dbColumn);
        System.out.println("schema:" + schema);
        System.out.println("privilege:" + privilege);
        System.out.println("grantor:" + grantor);
        System.out.println("isGrantable:" + isGrantable);
        System.out.println("grantee:" + grantee);
    }//from  ww w .  j a  v a2s .  com

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement stmt = null;//w w  w. j av a2  s  .c o m
    ResultSet rs = null;
    conn = getConnection();
    stmt = conn.createStatement();
    stmt.executeUpdate("insert into animals_table (name) values('newName')");
    rs = stmt.getGeneratedKeys();
    while (rs.next()) {
        ResultSetMetaData rsMetaData = rs.getMetaData();
        int columnCount = rsMetaData.getColumnCount();

        for (int i = 1; i <= columnCount; i++) {
            String key = rs.getString(i);
            System.out.println("key " + i + " is " + key);
        }
    }
    rs.close();
    stmt.close();
    conn.close();
}

From source file:ex4.java

public static void main(String[] params) {
    CommandLine commandLine = null;//w w  w  .j ava  2 s  .c o m
    String sqlpath = "", host = "", port = "3306", username = "", password = "", database = "";
    Boolean query = false;
    Option option_sql = Option.builder("s").argName("sql").hasArg()
            .desc("Path to a file containing a valid MySQL sql statement").build();
    Option option_hostname = Option.builder("h").argName("host").hasArg().desc("ClearDB MySQL Hostname")
            .build();
    Option option_port = Option.builder("n").argName("port").hasArg().desc("ClearDB MySQL Port").build();
    Option option_username = Option.builder("u").argName("username").hasArg().desc("ClearDB MySQL Username")
            .build();
    Option option_password = Option.builder("p").argName("password").hasArg().desc("ClearDB MySQL Password")
            .build();
    Option option_dbname = Option.builder("d").argName("dbname").hasArg().desc("ClearDB MySQL Database Name")
            .build();
    Option option_help = Option.builder("w").argName("wanthelp").hasArg().desc("Help").build();
    Option option_query = Option.builder().longOpt("query").desc("Query type SQL Statement").build();
    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(option_sql);
    options.addOption(option_hostname);
    options.addOption(option_port);
    options.addOption(option_username);
    options.addOption(option_password);
    options.addOption(option_dbname);
    options.addOption(option_query);
    options.addOption(option_help);

    try {
        commandLine = parser.parse(options, params);
    } catch (MissingOptionException e) {
        help(options);
    } catch (MissingArgumentException e) {
        help(options);
    } catch (ParseException e) {
        System.out.println(e);
    }

    if (commandLine.hasOption("w") || params.length == 0) {
        help(options);
    }

    if (commandLine.hasOption("s")) {
        sqlpath = commandLine.getOptionValue("s");
    } else {
        System.out.println("Missing path to a SQL statement file");
        help(options);
    }
    if (commandLine.hasOption("h")) {
        host = commandLine.getOptionValue("h");
    } else {
        System.out.println("Missing ClearDB hostname (e.g. us-cdbr-iron-east-??.cleardb.net)");
        help(options);
    }
    if (commandLine.hasOption("n")) {
        port = commandLine.getOptionValue("n");
    } else {
        System.out.println("Missing ClearDB Port Value.  Defaulting to 3306");
    }
    if (commandLine.hasOption("u")) {
        username = commandLine.getOptionValue("u");
    } else {
        System.out.println("Missing ClearDB Username");
        help(options);
    }
    if (commandLine.hasOption("p")) {
        password = commandLine.getOptionValue("p");
    } else {
        System.out.println("Missing ClearDB Password");
        help(options);
    }
    if (commandLine.hasOption("d")) {
        database = commandLine.getOptionValue("d");
    } else {
        System.out.println("Missing ClearDB Database Name");
        help(options);
    }

    if (commandLine.hasOption("query")) {
        query = true;
    }

    String connectionURL = new StringBuilder().append("jdbc:mysql://").append(host).append(":").append(port)
            .append("/").append(database).append("?reconnect=true").toString();

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println(e);
    }

    try {
        Connection con = DriverManager.getConnection(connectionURL, username, password);
        Statement stmt = con.createStatement();
        if (query) {
            System.out.println("Querying target MySQL DB ...");
            ResultSet rs = stmt.executeQuery(readFile(sqlpath, Charset.defaultCharset()));
            while (rs.next())
                System.out.println(rs.getInt("emp_no") + "  " + rs.getDate("birth_date") + "  "
                        + rs.getString("first_name") + "  " + rs.getString("last_name") + "  "
                        + rs.getString("gender") + "  " + rs.getDate("hire_date"));
        } else {
            System.out.println("Updating target MySQL DB ...");
            int result = stmt.executeUpdate(readFile(sqlpath, Charset.defaultCharset()));
            System.out.println(result);
        }
        con.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:de.tudarmstadt.ukp.csniper.resbuild.EvaluationItemFixer.java

public static void main(String[] args) {
    connect(HOST, DATABASE, USER, PASSWORD);

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

    // fetch coveredTexts of dubious items and clean it
    PreparedStatement select = null;
    try {//from  w ww  .  jav a  2s . co  m
        StringBuilder selectQuery = new StringBuilder();
        selectQuery.append("SELECT * FROM EvaluationItem ");
        selectQuery.append("WHERE LOCATE(coveredText, '  ') > 0 ");
        selectQuery.append("OR LOCATE('" + LRB + "', coveredText) > 0 ");
        selectQuery.append("OR LOCATE('" + RRB + "', coveredText) > 0 ");
        selectQuery.append("OR LEFT(coveredText, 1) = ' ' ");
        selectQuery.append("OR RIGHT(coveredText, 1) = ' ' ");

        select = connection.prepareStatement(selectQuery.toString());
        log.info("Running query [" + selectQuery.toString() + "].");
        ResultSet rs = select.executeQuery();

        while (rs.next()) {
            int id = rs.getInt("id");
            String coveredText = rs.getString("coveredText");

            try {
                // special handling of double whitespace: in this case, re-fetch the text
                if (coveredText.contains("  ")) {
                    coveredText = retrieveCoveredText(rs.getString("collectionId"), rs.getString("documentId"),
                            rs.getInt("beginOffset"), rs.getInt("endOffset"));
                }

                // replace bracket placeholders and trim the text
                coveredText = StringUtils.replace(coveredText, LRB, "(");
                coveredText = StringUtils.replace(coveredText, RRB, ")");
                coveredText = coveredText.trim();

                items.put(id, coveredText);
            } catch (IllegalArgumentException e) {
                failed.put(id, e.getMessage());
            }
        }
    } catch (SQLException e) {
        log.error("Exception while selecting: " + e.getMessage());
    } finally {
        closeQuietly(select);
    }

    // write logs
    BufferedWriter bwf = null;
    BufferedWriter bws = null;
    try {
        bwf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(LOG_FAILED)), "UTF-8"));
        for (Entry<Integer, String> e : failed.entrySet()) {
            bwf.write(e.getKey() + " - " + e.getValue() + "\n");
        }

        bws = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(new File(LOG_SUCCESSFUL)), "UTF-8"));
        for (Entry<Integer, String> e : items.entrySet()) {
            bws.write(e.getKey() + " - " + e.getValue() + "\n");
        }
    } catch (IOException e) {
        log.error("Got an IOException while writing the log files.");
    } finally {
        IOUtils.closeQuietly(bwf);
        IOUtils.closeQuietly(bws);
    }

    log.info("Texts for [" + items.size() + "] items need to be cleaned up.");

    // update the dubious items with the cleaned coveredText
    PreparedStatement update = null;
    try {
        String updateQuery = "UPDATE EvaluationItem SET coveredText = ? WHERE id = ?";

        update = connection.prepareStatement(updateQuery);
        int i = 0;
        for (Entry<Integer, String> e : items.entrySet()) {
            int id = e.getKey();
            String coveredText = e.getValue();

            // update item in database
            update.setString(1, coveredText);
            update.setInt(2, id);
            update.executeUpdate();
            log.debug("Updating " + id + " with [" + coveredText + "]");

            // show percentage of updated items
            i++;
            int part = (int) Math.ceil((double) items.size() / 100);
            if (i % part == 0) {
                log.info(i / part + "% finished (" + i + "/" + items.size() + ").");
            }
        }
    } catch (SQLException e) {
        log.error("Exception while updating: " + e.getMessage());
    } finally {
        closeQuietly(update);
    }

    closeQuietly(connection);
}

From source file:JDBCQuery.java

public static void main(String[] av) {
    try {/*from ww  w  . j av  a  2  s  . c o m*/
        System.out.println("Loading Driver (with Class.forName)");
        // Load the jdbc-odbc bridge driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        // Enable logging
        // DriverManager.setLogStream(System.err);

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection("jdbc:odbc:Companies", "ian", ""); // user, passwd

        // Any warnings generated by the connect?
        checkForWarning(conn.getWarnings());

        System.out.println("Creating Statement");
        Statement stmt = conn.createStatement();

        System.out.println("Executing Query");
        ResultSet rs = stmt.executeQuery("SELECT * FROM Companies");

        System.out.println("Retrieving Results");
        int i = 0;
        while (rs.next()) {

            System.out.println("Retrieving Company ID");
            int x = rs.getInt("CustNO");
            System.out.println("Retrieving Name");
            String s = rs.getString("Company");

            System.out.println("ROW " + ++i + ": " + x + "; " + s + "; " + ".");

        }

        rs.close(); // All done with that resultset
        stmt.close(); // All done with that statement
        conn.close(); // All done with that DB connection

    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException e) {
        System.out.println("Database access failed " + e);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;
    DatabaseMetaData meta = conn.getMetaData();
    // The Oracle database stores its table names as Upper-Case,
    // if you pass a table name in lowercase characters, it will not work.
    // MySQL database does not care if table name is uppercase/lowercase.
    ////from   w  ww. jav  a2  s.  c  om
    rs = meta.getImportedKeys(conn.getCatalog(), null, "survey");
    while (rs.next()) {
        String fkTableName = rs.getString("FKTABLE_NAME");
        String fkColumnName = rs.getString("FKCOLUMN_NAME");
        int fkSequence = rs.getInt("KEY_SEQ");
        System.out.println("getExportedKeys(): fkTableName=" + fkTableName);
        System.out.println("getExportedKeys(): fkColumnName=" + fkColumnName);
        System.out.println("getExportedKeys(): fkSequence=" + fkSequence);
    }

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;
    DatabaseMetaData meta = conn.getMetaData();
    // The Oracle database stores its table names as Upper-Case,
    // if you pass a table name in lowercase characters, it will not work.
    // MySQL database does not care if table name is uppercase/lowercase.
    ///* w w w .j  a  v a2s  .co  m*/
    rs = meta.getExportedKeys(conn.getCatalog(), null, "survey");
    while (rs.next()) {
        String fkTableName = rs.getString("FKTABLE_NAME");
        String fkColumnName = rs.getString("FKCOLUMN_NAME");
        int fkSequence = rs.getInt("KEY_SEQ");
        System.out.println("getExportedKeys(): fkTableName=" + fkTableName);
        System.out.println("getExportedKeys(): fkColumnName=" + fkColumnName);
        System.out.println("getExportedKeys(): fkSequence=" + fkSequence);
    }

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet indexInformation = null;
    DatabaseMetaData meta = conn.getMetaData();

    // The '_' character represents any single character.
    // The '%' character represents any sequence of zero
    // or more characters.
    indexInformation = meta.getIndexInfo(conn.getCatalog(), null, "survey", true, true);
    while (indexInformation.next()) {
        String dbCatalog = indexInformation.getString("TABLE_CATALOG");
        String dbSchema = indexInformation.getString("TABLE_SCHEMA");
        String dbTableName = indexInformation.getString("TABLE_NAME");
        boolean dbNoneUnique = indexInformation.getBoolean("NON_UNIQUE");
        String dbIndexQualifier = indexInformation.getString("INDEX_QUALIFIER");
        String dbIndexName = indexInformation.getString("INDEX_NAME");
        short dbType = indexInformation.getShort("TYPE");
        short dbOrdinalPosition = indexInformation.getShort("ORDINAL_POSITION");
        String dbColumnName = indexInformation.getString("COLUMN_NAME");
        String dbAscOrDesc = indexInformation.getString("ASC_OR_DESC");
        int dbCardinality = indexInformation.getInt("CARDINALITY");
        int dbPages = indexInformation.getInt("PAGES");
        String dbFilterCondition = indexInformation.getString("FILTER_CONDITION");

        System.out.println("index name=" + dbIndexName);
        System.out.println("table=" + dbTableName);
        System.out.println("column=" + dbColumnName);
        System.out.println("catalog=" + dbCatalog);
        System.out.println("schema=" + dbSchema);
        System.out.println("nonUnique=" + dbNoneUnique);
        System.out.println("indexQualifier=" + dbIndexQualifier);
        System.out.println("type=" + dbType);
        System.out.println("ordinalPosition=" + dbOrdinalPosition);
        System.out.println("ascendingOrDescending=" + dbAscOrDesc);
        System.out.println("cardinality=" + dbCardinality);
        System.out.println("pages=" + dbPages);
        System.out.println("filterCondition=" + dbFilterCondition);
    }/*from   ww w.j  a  va 2  s. c  o m*/

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar, PRIMARY KEY (id) );");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rs = null;
    DatabaseMetaData meta = conn.getMetaData();
    // The Oracle database stores its table names as Upper-Case,
    // if you pass a table name in lowercase characters, it will not work.
    // MySQL database does not care if table name is uppercase/lowercase.
    ////  ww  w. j  av  a2  s. c  om
    rs = meta.getPrimaryKeys(null, null, "survey");

    java.util.List list = new java.util.ArrayList();
    while (rs.next()) {
        String columnName = rs.getString("COLUMN_NAME");
        System.out.println("getPrimaryKeys(): columnName=" + columnName);
    }

    st.close();
    conn.close();
}