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

public static void main(String[] args) throws Exception {

    Class.forName(DRIVER);/* ww  w  . j a  v a2 s .c  o  m*/
    Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("SELECT * FROM users");

    ResultSetMetaData metadata = resultSet.getMetaData();
    int columnCount = metadata.getColumnCount();

    ArrayList<String> columns = new ArrayList<String>();
    for (int i = 1; i < columnCount; i++) {
        String columnName = metadata.getColumnName(i);
        columns.add(columnName);
    }

    while (resultSet.next()) {
        for (String columnName : columns) {
            String value = resultSet.getString(columnName);
            System.out.println(columnName + " = " + value);
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String url = "jdbc:odbc:databaseName";
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    String user = "guest";
    String password = "guest";

    String theStatement = "SELECT lastname, firstname FROM autors";

    try {//from  www  . ja v  a  2  s .c  o m
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        Statement queryAuthors = connection.createStatement();
        ResultSet theResults = queryAuthors.executeQuery(theStatement);

        queryAuthors.close();
    } catch (ClassNotFoundException cnfe) {
        System.err.println(cnfe);
    } catch (SQLException sqle) {
        String sqlMessage = sqle.getMessage();
        String sqlState = sqle.getSQLState();
        int vendorCode = sqle.getErrorCode();
        System.err.println("Exception occurred:");
        System.err.println("Message: " + sqlMessage);
        System.err.println("SQL state: " + sqlState);
        System.err.println("Vendor code: " + vendorCode + "\n----------------");
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String url = "jdbc:odbc:technical_library";
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    String theStatement = "SELECT authid, lastname, firstname, email FROM authors ORDER BY authid";

    try {//from   w  w  w  . ja v a  2  s .com
        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, "guest", "guest");
        Statement queryAuthors = connection.createStatement();
        ResultSet results = queryAuthors.executeQuery(theStatement);

        String lastname, firstname, email;
        int id;
        while (results.next()) {
            id = results.getInt(1);
            lastname = results.getString(2);
            firstname = results.getString(3);
            email = results.getString(4);

            if (results.wasNull()) {
                email = "no email";
            }
            System.out.println(Integer.toString(id) + ", " + lastname.trim() + ", " + firstname.trim() + ", "
                    + email.trim());
        }
        queryAuthors.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:com.linuxrouter.netcool.test.DbPoolTest.java

public static void main(String[] args) {
    String host = "192.168.0.201";
    String port = "4100";
    String dbName = "alerts";
    String url = "jdbc:sybase:Tds:" + host + ":" + port + "/" + dbName;
    Driver drv = new com.sybase.jdbc3.jdbc.SybDriver();
    try {//from w  ww .  j a va  2s .  c  o  m
        DriverManager.registerDriver(drv);
    } catch (SQLException ex) {
        Logger.getLogger(DbPoolTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, "root", "omni12@#");
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            null);
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool);
    PoolingDataSource<PoolableConnection> poolingDataSource = new PoolingDataSource<>(connectionPool);
    try {
        Connection con = poolingDataSource.getConnection();
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from alerts.status");
        int x = 0;
        while (rs.next()) {
            //System.out.println(":::" + rs.getString(1));
            x++;
        }
        System.out.println("::::::" + x);
    } catch (SQLException ex) {
        Logger.getLogger(DbPoolTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:Contacts");
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = stmt.executeQuery("select * from employee");
    rs.moveToInsertRow();//from   ww w  .  ja va2s. co m

    rs.updateInt(1, 150);
    rs.updateString("First_Name", "Nigel");
    rs.updateString("Last_Name", "Thornebury");

    rs.insertRow();
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:Contacts");
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = stmt.executeQuery("select * from employee");
    rs.moveToInsertRow();/*from  w w w  .jav  a 2  s  . co  m*/

    rs.updateInt("Contact_ID", 150);
    rs.updateString("First_Name", "Nigel");
    rs.updateString("Last_Name", "Thornebury");

    rs.insertRow();
}

From source file:History.PieChart_DB.java

public static void main(String[] args) throws Exception {

    String mobilebrands[] = { "IPhone 5s", "SamSung Grand", "MotoG", "Nokia Lumia" };
    int statOfRepair = 0;
    java.util.Date now = new java.util.Date();
    String adminDate = (now.getYear() + 1900) + "-" + (now.getMonth() + 1) + "-" + now.getDate();
    /* Create MySQL Database Connection */
    Class.forName("com.mysql.jdbc.Driver");
    Connection connect = ConnectDatabase.connectDb("win", "win016");

    Statement statement = connect.createStatement();
    ResultSet resultSet = statement
            .executeQuery("SELECT COUNT(transID) AS statRepair FROM `Transaction` WHERE dateTime LIKE \'"
                    + adminDate + "%\' AND action LIKE 'Repair'");
    DefaultPieDataset dataset = new DefaultPieDataset();

    while (resultSet.next()) {
        dataset.setValue(resultSet.getString("statRepair"),
                Double.parseDouble(resultSet.getString("unit_sale")));
    }/*ww  w .j  a  va 2s . co m*/

    JFreeChart chart = ChartFactory.createPieChart("History", // chart title           
            dataset, // data           
            true, // include legend          
            true, false);

    int width = 560; /* Width of the image */
    int height = 370; /* Height of the image */
    File pieChart = new File("Pie_Chart.jpeg");
    ChartUtilities.saveChartAsJPEG(pieChart, chart, width, height);
}

From source file:Select.java

public static void main(String args[]) {
    String url = "jdbc:msql://carthage.imaginary.com/ora";
    Connection con = null;/*  w w  w. ja v a2 s . com*/

    try {
        String driver = "com.imaginary.sql.msql.MsqlDriver";

        Class.forName(driver).newInstance();
    } catch (Exception e) {
        System.out.println("Failed to load mSQL driver.");
        return;
    }
    try {
        con = DriverManager.getConnection(url, "borg", "");
        Statement select = con.createStatement();
        ResultSet result = select.executeQuery("SELECT test_id, test_val FROM test");

        System.out.println("Got results:");
        while (result.next()) { // process results one row at a time
            int key = result.getInt(1);
            String val = result.getString(2);

            System.out.println("key = " + key);
            System.out.println("val = " + val);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:JndiDataSource.java

public static void main(String args[]) throws Exception {
    String sp = "com.sun.jndi.fscontext.RefFSContextFactory";
    String file = "file:/e:/JNDI";
    String dataSourceName = "jdbc/myDatabase";

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, sp);
    env.put(Context.PROVIDER_URL, file);
    ctx = new InitialContext(env);

    bindDataSource(ctx, dataSourceName);

    DataSource ds = null;/* w w w  .j a  v  a 2 s  .co m*/
    ds = (DataSource) ctx.lookup(dataSourceName);

    Connection conn = ds.getConnection();

    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT Name FROM Employees");

    while (rs.next())
        System.out.println(rs.getString("name"));

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

    ctx.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    try {//from  w w  w  . j a va2  s  .c  o m
        String url = "jdbc:odbc:yourdatabasename";
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String user = "guest";
        String password = "guest";

        FileInputStream fis = new FileInputStream("sometextfile.txt");

        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        Statement createTable = connection.createStatement();
        createTable.executeUpdate("CREATE TABLE source_code (name char(20), source LONGTEXT)");
        String ins = "INSERT INTO source_code VALUES(?,?)";
        PreparedStatement statement = connection.prepareStatement(ins);

        statement.setString(1, "TryInputStream2");
        statement.setAsciiStream(2, fis, fis.available());

        int rowsUpdated = statement.executeUpdate();
        System.out.println("Rows affected: " + rowsUpdated);
        Statement getCode = connection.createStatement();
        ResultSet theCode = getCode.executeQuery("SELECT name,source FROM source_code");
        BufferedReader reader = null;
        String input = null;

        while (theCode.next()) {
            reader = new BufferedReader(new InputStreamReader(theCode.getAsciiStream(2)));
            while ((input = reader.readLine()) != null) {
                System.out.println(input);
            }
        }
        connection.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}