Example usage for java.sql Statement execute

List of usage examples for java.sql Statement execute

Introduction

In this page you can find the example usage for java.sql Statement execute.

Prototype

boolean execute(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which may return multiple results.

Usage

From source file:com.alibaba.cobar.manager.test.ConnectionTest.java

/**
 * @param args//from  w  w  w. ja  v a2  s  .co  m
 */
public static void main(String[] args) {
    try {
        BasicDataSource ds = new BasicDataSource();
        ds.setUsername("test");
        ds.setPassword("");
        ds.setUrl("jdbc:mysql://10.20.153.178:9066/");
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setMaxActive(-1);
        ds.setMinIdle(0);
        ds.setTimeBetweenEvictionRunsMillis(600000);
        ds.setNumTestsPerEvictionRun(Integer.MAX_VALUE);
        ds.setMinEvictableIdleTimeMillis(GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
        Connection conn = ds.getConnection();

        Statement stm = conn.createStatement();
        stm.execute("show @@version");

        ResultSet rst = stm.getResultSet();
        rst.next();
        String version = rst.getString("VERSION");

        System.out.println(version);

    } catch (Exception exception) {
        System.out.println("10.20.153.178:9066   " + exception.getMessage() + exception);
    }
}

From source file:TableMaker.java

public static void main(String[] args) throws Exception {
    Class.forName(jdbcDriver);/* w w w. j av  a2  s .  c o  m*/
    url += dbName;
    Connection con = null;
    Statement stmt = null;
    con = DriverManager.getConnection(url);
    stmt = con.createStatement();
    stmt.execute(SQLCreate);
    con.close();
    if (con != null) {
        con.close();
    }
    if (stmt != null) {
        stmt.close();
    }

}

From source file:Main.java

public static void main(String args[]) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String url = "jdbc:oracle:thin:@localhost:1521:XE";
    String userName = "suru";
    String password = "password";
    Connection con = DriverManager.getConnection(url, userName, password);
    System.out.println("Connection success!");
    Statement stmt = con.createStatement();
    String sql = "CREATE TABLE EMP ( ID NUMBER(5) PRIMARY KEY, NAME VARCHAR2(50))";
    stmt.execute(sql);
    System.out.println("Table created successfully!");
    stmt.close();/*from  ww w  .j av  a  2  s .c  o  m*/
    con.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection connection = null;
    Class.forName("com.mysql.jdbc.Driver");

    String url = "jdbc:mysql://localhost/testdb";
    String user = "root";
    String password = "";
    connection = DriverManager.getConnection(url, user, password);

    Statement stmt = connection.createStatement();
    String sql = "INSERT INTO users (name, address) VALUES ('Foo', 'Street')";
    stmt.execute(sql);
    connection.close();/*from  w  w  w .  j a v a  2 s  .  c  om*/
}

From source file:DataUpdater.java

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

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    DriverManager.registerDriver(new JdbcOdbcDriver());
    String url = "jdbc:odbc:Contacts";

    Connection con = DriverManager.getConnection(url);
    Statement stmt = con.createStatement();
    String SQLCommand = "UPDATE CONTACT_INFO " + "SET STREET = '58 Broadway', ZIP = '10008' "
            + "WHERE First_Name = 'Michael' AND " + "Last_Name ='Corleone';";

    stmt.execute(SQLCommand);
    con.close();/*from   w  ww .  j  a  v  a2 s .co m*/
}

From source file:ExecuteMethod.java

public static void main(String[] args) {
    Connection conn = null;/* w w w . j a  va  2  s  .co m*/
    Statement stmt = null;
    ResultSet rs = null;
    boolean executeResult;
    try {
        String driver = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driver).newInstance();
        System.out.println("Connecting to database...");
        String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
        conn = DriverManager.getConnection(jdbcUrl, "test", "mypwd");
        stmt = conn.createStatement();

        String sql = "INSERT INTO Employees VALUES" + "(1,'G','4351',{d '1996-12-31'},500)";
        executeResult = stmt.execute(sql);
        processExecute(stmt, executeResult);

        sql = "SELECT * FROM Employees ORDER BY hiredate";
        executeResult = stmt.execute(sql);
        processExecute(stmt, executeResult);
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
}

From source file:mx.com.pixup.portal.demo.DemoDisqueraDelete.java

public static void main(String[] args) {
    System.out.println("BIENVENIDO A PIXUP");
    System.out.println("Mantenimiento catlogo disquera");
    System.out.println("Inserte el nombre de la disquera a eliminar: ");

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    Connection connection = null;
    Statement statement = null;
    try {/*from w ww  . ja  v  a 2s .  c om*/
        String nombreDisquera = br.readLine();
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("admin");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/pixup");

        connection = dataSource.getConnection();
        statement = connection.createStatement();

        String sql = "delete from disquera where nombre = '" + nombreDisquera + "'";

        statement.execute(sql);

        System.out.println("Disquera: " + nombreDisquera + " eliminada con xito");

    } catch (Exception e) {
        System.out.println("Error en el sistema, intente ms tarde!!");
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:ExecSQL.java

public static void main(String args[]) {
        try {/*from ww w .ja  v  a 2s .c o  m*/
            Scanner in;
            if (args.length == 0)
                in = new Scanner(System.in);
            else
                in = new Scanner(new File(args[0]));

            Connection conn = getConnection();
            try {
                Statement stat = conn.createStatement();

                while (true) {
                    if (args.length == 0)
                        System.out.println("Enter command or EXIT to exit:");

                    if (!in.hasNextLine())
                        return;

                    String line = in.nextLine();
                    if (line.equalsIgnoreCase("EXIT"))
                        return;
                    if (line.trim().endsWith(";")) // remove trailing semicolon
                    {
                        line = line.trim();
                        line = line.substring(0, line.length() - 1);
                    }
                    try {
                        boolean hasResultSet = stat.execute(line);
                        if (hasResultSet)
                            showResultSet(stat);
                    } catch (SQLException ex) {
                        for (Throwable e : ex)
                            e.printStackTrace();
                    }
                }
            } finally {
                conn.close();
            }
        } catch (SQLException e) {
            for (Throwable t : e)
                t.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

From source file:mx.com.pixup.portal.demo.DemoDisqueraUpdate.java

public static void main(String[] args) {
    System.out.println("BIENVENIDO A PIXUP");
    System.out.println("Mantenimiento catlogo disquera");
    System.out.println("Actualizacin de Disquera");

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;/* w ww  . j av a  2s  .  c  o  m*/
    try {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("admin");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/pixup");

        connection = dataSource.getConnection();
        statement = connection.createStatement();

        String sql = "select id, nombre from disquera order by nombre";

        resultSet = statement.executeQuery(sql);

        System.out.println("Id Disquera: \t Nombre Disquera");
        while (resultSet.next()) {
            System.out.println(resultSet.getInt("id") + " \t " + resultSet.getString("nombre"));
        }

        System.out.println("Proporcione el id de la disquera a actualizar: ");
        String idDisquera = br.readLine();

        System.out.println("Proporcione el nuevo nombre de la disquera: ");
        String nombreDisquera = br.readLine();

        sql = "update disquera set nombre = '" + nombreDisquera + "' where id = " + idDisquera;

        statement.execute(sql);

        System.out.println("Disqueras Actualizadas:");

        sql = "select id, nombre from disquera order by nombre desc";

        resultSet = statement.executeQuery(sql);

        System.out.println("Id Disquera: \t Nombre Disquera");
        while (resultSet.next()) {
            System.out.println(resultSet.getInt("id") + " \t " + resultSet.getString("nombre"));
        }

    } catch (Exception e) {
        System.out.println("Error en el sistema, intente ms tarde!!");
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:ExecuteSQL.java

public static void main(String[] args) {
    Connection conn = null; // Our JDBC connection to the database server
    try {//from w  ww. ja  v  a2 s.c o m
        String driver = null, url = null, user = "", password = "";

        // Parse all the command-line arguments
        for (int n = 0; n < args.length; n++) {
            if (args[n].equals("-d"))
                driver = args[++n];
            else if (args[n].equals("-u"))
                user = args[++n];
            else if (args[n].equals("-p"))
                password = args[++n];
            else if (url == null)
                url = args[n];
            else
                throw new IllegalArgumentException("Unknown argument.");
        }

        // The only required argument is the database URL.
        if (url == null)
            throw new IllegalArgumentException("No database specified");

        // If the user specified the classname for the DB driver, load
        // that class dynamically. This gives the driver the opportunity
        // to register itself with the DriverManager.
        if (driver != null)
            Class.forName(driver);

        // Now open a connection the specified database, using the
        // user-specified username and password, if any. The driver
        // manager will try all of the DB drivers it knows about to try to
        // parse the URL and connect to the DB server.
        conn = DriverManager.getConnection(url, user, password);

        // Now create the statement object we'll use to talk to the DB
        Statement s = conn.createStatement();

        // Get a stream to read from the console
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // Loop forever, reading the user's queries and executing them
        while (true) {
            System.out.print("sql> "); // prompt the user
            System.out.flush(); // make the prompt appear now.
            String sql = in.readLine(); // get a line of input from user

            // Quit when the user types "quit".
            if ((sql == null) || sql.equals("quit"))
                break;

            // Ignore blank lines
            if (sql.length() == 0)
                continue;

            // Now, execute the user's line of SQL and display results.
            try {
                // We don't know if this is a query or some kind of
                // update, so we use execute() instead of executeQuery()
                // or executeUpdate() If the return value is true, it was
                // a query, else an update.
                boolean status = s.execute(sql);

                // Some complex SQL queries can return more than one set
                // of results, so loop until there are no more results
                do {
                    if (status) { // it was a query and returns a ResultSet
                        ResultSet rs = s.getResultSet(); // Get results
                        printResultsTable(rs, System.out); // Display them
                    } else {
                        // If the SQL command that was executed was some
                        // kind of update rather than a query, then it
                        // doesn't return a ResultSet. Instead, we just
                        // print the number of rows that were affected.
                        int numUpdates = s.getUpdateCount();
                        System.out.println("Ok. " + numUpdates + " rows affected.");
                    }

                    // Now go see if there are even more results, and
                    // continue the results display loop if there are.
                    status = s.getMoreResults();
                } while (status || s.getUpdateCount() != -1);
            }
            // If a SQLException is thrown, display an error message.
            // Note that SQLExceptions can have a general message and a
            // DB-specific message returned by getSQLState()
            catch (SQLException e) {
                System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
            }
            // Each time through this loop, check to see if there were any
            // warnings. Note that there can be a whole chain of warnings.
            finally { // print out any warnings that occurred
                SQLWarning w;
                for (w = conn.getWarnings(); w != null; w = w.getNextWarning())
                    System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
            }
        }
    }
    // Handle exceptions that occur during argument parsing, database
    // connection setup, etc. For SQLExceptions, print the details.
    catch (Exception e) {
        System.err.println(e);
        if (e instanceof SQLException)
            System.err.println("SQL State: " + ((SQLException) e).getSQLState());
        System.err.println(
                "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>");
    }

    // Be sure to always close the database connection when we exit,
    // whether we exit because the user types 'quit' or because of an
    // exception thrown while setting things up. Closing this connection
    // also implicitly closes any open statements and result sets
    // associated with it.
    finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}