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:MainClass.java

public static void main(String[] args) {
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;/*from  ww w  . ja  v  a  2 s  . c o m*/

    try {
        connection = getConnection();
        // Do work with connection
        statement = connection.createStatement();
        String selectEmployeesSQL = "SELECT * FROM employees";
        resultSet = statement.executeQuery(selectEmployeesSQL);

        while (resultSet.next()) {
            printEmployee(resultSet);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
            } // nothing we can do
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
            } // nothing we can do
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            } // nothing we can do
        }
    }
}

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')");

    st = conn.createStatement();// www. j  a v a  2s .  co  m
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    ResultSetMetaData rsMetaData = rs.getMetaData();

    int numberOfColumns = rsMetaData.getColumnCount();
    System.out.println("resultSet MetaData column Count=" + numberOfColumns);

    for (int i = 1; i <= numberOfColumns; i++) {
        System.out.println("column MetaData ");
        System.out.println("column number " + i);
        System.out.println(rsMetaData.getColumnDisplaySize(i));
        System.out.println(rsMetaData.getColumnLabel(i));
        System.out.println(rsMetaData.getColumnName(i));
        System.out.println(rsMetaData.getColumnType(i));
        System.out.println(rsMetaData.getColumnTypeName(i));
        System.out.println(rsMetaData.getColumnClassName(i));
        System.out.println(rsMetaData.getTableName(i));
        System.out.println(rsMetaData.getPrecision(i));
        System.out.println(rsMetaData.getScale(i));
        System.out.println(rsMetaData.isAutoIncrement(i));
        System.out.println(rsMetaData.isCurrency(i));
        System.out.println(rsMetaData.isWritable(i));
        System.out.println(rsMetaData.isDefinitelyWritable(i));
        System.out.println(rsMetaData.isNullable(i));
        System.out.println(rsMetaData.isReadOnly(i));
        System.out.println(rsMetaData.isCaseSensitive(i));
        System.out.println(rsMetaData.isSearchable(i));
        System.out.println(rsMetaData.isSigned(i));
        System.out.println(rsMetaData.getCatalogName(i));
        System.out.println(rsMetaData.getSchemaName(i));
    }
    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int, myDate TIMESTAMP );");

    String INSERT_RECORD = "insert into survey(id) values(?)";

    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
    pstmt.setString(1, "1");
    pstmt.executeUpdate();//from   ww  w  . j  a v a 2s .  co  m

    ResultSet rs = st.executeQuery("SELECT * FROM survey");
    outputResultSet(rs);

    pstmt.setString(1, "2");
    pstmt.executeUpdate();

    rs = st.executeQuery("SELECT * FROM survey");
    outputResultSet(rs);

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

From source file:ResultSetMetaDataExample.java

public static void main(String args[]) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:Inventory", "", "");
    Statement stmt = con.createStatement();

    boolean notDone = true;
    String sqlStr = null;/*from  w  w w .  j a v  a  2 s  .  co m*/
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    while (notDone) {
        sqlStr = br.readLine();
        if (sqlStr.startsWith("SELECT") || sqlStr.startsWith("select")) {
            ResultSet rs = stmt.executeQuery(sqlStr);
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            for (int x = 1; x <= columnCount; x++) {
                String columnName = rsmd.getColumnName(x);
                System.out.print(columnName);
            }
            while (rs.next()) {
                for (int x = 1; x <= columnCount; x++) {
                    if (rsmd.getColumnTypeName(x).compareTo("CURRENCY") == 0)
                        System.out.print("$");
                    String resultStr = rs.getString(x);
                    System.out.print(resultStr + "\t");
                }
            }
        } else if (sqlStr.startsWith("exit"))
            notDone = false;
    }
    stmt.close();
    con.close();
}

From source file:ex4.java

public static void main(String[] params) {
    CommandLine commandLine = null;/*  ww  w . j a va 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:GetColumnNamesFromResultSet_Oracle.java

public static void main(String[] args) {
    Connection conn = null;/*  ww w.  ja  v a 2 s.  co m*/
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        // prepare query
        String query = "select id, name, age from employees";
        // create a statement
        stmt = conn.createStatement();
        // execute query and return result as a ResultSet
        rs = stmt.executeQuery(query);
        // get the column names from the ResultSet
        getColumnNames(rs);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // release database resources
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:GetColumnNamesFromResultSet_MySQL.java

public static void main(String[] args) {
    Connection conn = null;//from  w  w w . j a v a  2 s .  co m
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        // prepare query
        String query = "select id, name, age from employees";
        // create a statement
        stmt = conn.createStatement();
        // execute query and return result as a ResultSet
        rs = stmt.executeQuery(query);
        // get the column names from the ResultSet
        getColumnNames(rs);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        // release database resources
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement stmt = conn.createStatement();

    stmt.executeUpdate("create table survey (id DECIMAL, name BINARY );");

    String sql = "INSERT INTO survey (id) VALUES(?)";
    PreparedStatement pstmt = conn.prepareStatement(sql);

    pstmt.setBigDecimal(1, new BigDecimal("1.00000"));

    // insert the data
    pstmt.executeUpdate();//from   ww w .  j a va 2 s .  c o m

    ResultSet rs = stmt.executeQuery("SELECT * FROM survey");
    while (rs.next()) {
        System.out.print(rs.getString(1));
    }

    rs.close();
    stmt.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st = conn.createStatement();/*www . jav  a 2 s. co  m*/
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    while (rs.next()) {
        String name = rs.getString(2);
        System.out.println(name);
    }

    rs.close();
    st.close();
    conn.close();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st = conn.createStatement();//from  w ww. jav a2  s  .  co m
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    while (rs.next()) {
        String name = rs.getString("name");
        System.out.println(name);
    }

    rs.close();
    st.close();
    conn.close();

}