Example usage for java.sql Statement executeUpdate

List of usage examples for java.sql Statement executeUpdate

Introduction

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

Prototype

int executeUpdate(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);//from w w  w.  j a va  2  s  . co m

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    Statement stmt = connection.createStatement();
    //     Column Name          SQLServer Type           Java Type
    String sql = "CREATE TABLE sqlserver_all_table(" + "col_boolean          BIT, " // boolean
            + "col_byte             TINYINT, " // byte
            + "col_short            SMALLINT, " // short
            + "col_int              INTEGER, " // int
            + "col_float            REAL, " // float
            + "col_double           DOUBLE PRECISION, " // double
            + "col_bigdecimal       DECIMAL(13,0), " // BigDecimal; can also be NUMERIC(p,s)
            + "col_string           VARCHAR(254), " // String
            + "col_date             DATETIME, " // Date
            + "col_time             DATETIME, " // Time
            + "col_timestamp        TIMESTAMP, " // Timestamp
            + "col_characterstream  TEXT, " // CharacterStream or AsciiStream (< 2 GBytes)
            + "col_binarystream     IMAGE)"; // BinaryStream (< 2 GBytes)

    stmt.executeUpdate(sql);
}

From source file:CreateRef.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;//  ww  w  .j  a va2 s . c o m
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        String createManagers = "CREATE TABLE MANAGERS OF MANAGER "
                + "(OID REF(MANAGER) VALUES ARE SYSTEM GENERATED)";

        String insertManager1 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES "
                + "(000001, 'MONTOYA', 'ALFREDO', '8317225600')";

        String insertManager2 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES "
                + "(000002, 'HASKINS', 'MARGARET', '4084355600')";

        String insertManager3 = "INSERT INTO MANAGERS " + "(MGR_ID, LAST_NAME, FIRST_NAME, PHONE) VALUES "
                + "(000003, 'CHEN', 'HELEN', '4153785600')";

        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();
        stmt.executeUpdate(createManagers);

        con.setAutoCommit(false);

        stmt.addBatch(insertManager1);
        stmt.addBatch(insertManager2);
        stmt.addBatch(insertManager3);
        int[] updateCounts = stmt.executeBatch();

        con.commit();

        System.out.println("Update count for:  ");
        for (int i = 0; i < updateCounts.length; i++) {
            System.out.print("    command " + (i + 1) + " = ");
            System.out.println(updateCounts[i]);
        }

        stmt.close();
        con.close();

    } catch (BatchUpdateException b) {
        System.err.println("-----BatchUpdateException-----");
        System.err.println("Message:  " + b.getMessage());
        System.err.println("SQLState:  " + b.getSQLState());
        System.err.println("Vendor:  " + b.getErrorCode());
        System.err.print("Update counts for successful commands:  ");
        int[] rowsUpdated = b.getUpdateCounts();
        for (int i = 0; i < rowsUpdated.length; i++) {
            System.err.print(rowsUpdated[i] + "   ");
        }
        System.err.println("");
    } catch (SQLException ex) {
        System.err.println("------SQLException------");
        System.err.println("Error message:  " + ex.getMessage());
        System.err.println("SQLState:  " + ex.getSQLState());
        System.err.println("Vendor:  " + ex.getErrorCode());
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String driverName = "oracle.jdbc.driver.OracleDriver";
    Class.forName(driverName);//from  ww  w . j  a  v  a 2  s.  c  o m

    String serverName = "127.0.0.1";
    String portNumber = "1521";
    String sid = "mydatabase";
    String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
    String username = "username";
    String password = "password";
    Connection connection = DriverManager.getConnection(url, username, password);

    Statement stmt = connection.createStatement();

    stmt.execute("CREATE TYPE number_varray AS VARRAY(10) OF NUMBER(12, 2)");

    stmt.execute("CREATE TYPE my_object AS OBJECT(col_string2 VARCHAR(30), col_int2 INTEGER)");

    //    Column Name          Oracle Type             Java Type
    String sql = "CREATE TABLE oracle_all_table(" + "col_short           SMALLINT, " // short
            + "col_int             INTEGER, " // int
            + "col_float           REAL, " // float; can also be NUMBER
            + "col_double          DOUBLE PRECISION, " // double; can also be FLOAT or NUMBER
            + "col_bigdecimal      DECIMAL(13,0), " // BigDecimal
            + "col_string          VARCHAR2(254), " // String; can also be CHAR(n)
            + "col_characterstream LONG, " // CharacterStream or AsciiStream
            + "col_bytes           RAW(2000), " // byte[]; can also be LONG RAW(n)
            + "col_binarystream    RAW(2000), " // BinaryStream; can also be LONG RAW(n)
            + "col_timestamp       DATE, " // Timestamp
            + "col_clob            CLOB, " // Clob
            + "col_blob            BLOB, " // Blob; can also be BFILE
            + "col_array           number_varray, " // oracle.sql.ARRAY
            + "col_object          my_object)"; // oracle.sql.OBJECT

    stmt.executeUpdate(sql);

}

From source file:edu.clemson.cs.nestbed.server.tools.BuildTestbed.java

public static void main(String[] args) {
    try {/* w  w w.j  ava2  s.  c om*/
        BasicConfigurator.configure();
        //loadProperties();

        if (args.length < 2) {
            System.out.println("Usage: BuildTestbed <testbedID> <inputfile>");
            System.exit(0);
        }

        int testbedID = Integer.parseInt(args[0]);
        String filename = args[1];
        Connection conn = null;
        Statement statement = null;
        MoteSqlAdapter adapter = new MoteSqlAdapter();
        Map<Integer, Mote> motes = adapter.readMotes();

        log.info(motes);

        String connStr = System.getProperty("nestbed.options.databaseConnectionString");
        log.info("connStr: " + connStr);

        conn = DriverManager.getConnection(connStr);
        statement = conn.createStatement();

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));

        String line;
        while ((line = in.readLine()) != null) {
            StringTokenizer tokenizer = new StringTokenizer(line);
            int address = Integer.parseInt(tokenizer.nextToken());
            String serial = tokenizer.nextToken();
            int xLoc = Integer.parseInt(tokenizer.nextToken());
            int yLoc = Integer.parseInt(tokenizer.nextToken());

            log.info("Input Mote:\n" + "-----------\n" + "address:  " + address + "\n" + "serial:   " + serial
                    + "\n" + "xLoc:     " + xLoc + "\n" + "yLoc:     " + yLoc);

            for (Mote i : motes.values()) {
                if (i.getMoteSerialID().equals(serial)) {
                    String query = "INSERT INTO MoteTestbedAssignments" + "(testbedID, moteID, moteAddress,"
                            + " moteLocationX, moteLocationY) VALUES (" + testbedID + ", " + i.getID() + ", "
                            + address + ", " + xLoc + ", " + yLoc + ")";
                    log.info(query);
                    statement.executeUpdate(query);
                }
            }
        }
        conn.commit();
    } catch (Exception ex) {
        log.error("Exception in main", ex);
    }
}

From source file:Main.java

public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;/*from  www  .j ava2s.co m*/
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        Vector dataTypes = getDataTypes(con);

        String tableName;
        String columnName;
        String sqlType;
        String prompt = "Enter the new table name and hit Return: ";
        tableName = getInput(prompt);
        String createTableString = "create table " + tableName + " (";

        String commaAndSpace = ", ";
        boolean firstTime = true;
        while (true) {
            System.out.println("");
            prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: ";
            columnName = getInput(prompt);
            if (firstTime) {
                if (columnName.length() == 0) {
                    System.out.print("Need at least one column;");
                    System.out.println(" please try again");
                    continue;
                } else {
                    createTableString += columnName + " ";
                    firstTime = false;
                }
            } else if (columnName.length() == 0) {
                break;
            } else {
                createTableString += commaAndSpace + columnName + " ";
            }

            String localTypeName = null;
            String paramString = "";
            while (true) {
                System.out.println("");
                System.out.println("LIST OF TYPES YOU MAY USE:  ");
                boolean firstPrinted = true;
                int length = 0;
                for (int i = 0; i < dataTypes.size(); i++) {
                    DataType dataType = (DataType) dataTypes.get(i);
                    if (!dataType.needsToBeSet()) {
                        if (!firstPrinted)
                            System.out.print(commaAndSpace);
                        else
                            firstPrinted = false;
                        System.out.print(dataType.getSQLType());
                        length += dataType.getSQLType().length();
                        if (length > 50) {
                            System.out.println("");
                            length = 0;
                            firstPrinted = true;
                        }
                    }
                }
                System.out.println("");

                int index;
                prompt = "Enter a column type " + "from the list and hit Return:  ";
                sqlType = getInput(prompt);
                for (index = 0; index < dataTypes.size(); index++) {
                    DataType dataType = (DataType) dataTypes.get(index);
                    if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
                        break;
                    }
                }

                localTypeName = null;
                paramString = "";
                if (index < dataTypes.size()) { // there was a match
                    String params;
                    DataType dataType = (DataType) dataTypes.get(index);
                    params = dataType.getParams();
                    localTypeName = dataType.getLocalType();
                    if (params != null) {
                        prompt = "Enter " + params + ":  ";
                        paramString = "(" + getInput(prompt) + ")";
                    }
                    break;
                } else { // use the name as given
                    prompt = "Are you sure?  " + "Enter 'y' or 'n' and hit Return:  ";
                    String check = getInput(prompt) + " ";
                    check = check.toLowerCase().substring(0, 1);
                    if (check.equals("n"))
                        continue;
                    else {
                        localTypeName = sqlType;
                        break;
                    }
                }
            }

            createTableString += localTypeName + paramString;

        }

        createTableString += ")";
        System.out.println("");
        System.out.print("Your CREATE TABLE statement as ");
        System.out.println("sent to your DBMS:  ");
        System.out.println(createTableString);
        System.out.println("");

        stmt.executeUpdate(createTableString);

        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:CreateNewType.java

public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;//from  w  w  w  . jav a 2s.c o m
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        String typeToCreate = null;
        String prompt = "Enter 's' to create a structured type " + "or 'd' to create a distinct type\n"
                + "and hit Return: ";
        do {
            typeToCreate = getInput(prompt) + " ";
            typeToCreate = typeToCreate.toLowerCase().substring(0, 1);
        } while (!(typeToCreate.equals("s") || typeToCreate.equals("d")));

        Vector dataTypes = getDataTypes(con, typeToCreate);

        String typeName;
        String attributeName;
        String sqlType;
        prompt = "Enter the new type name and hit Return: ";
        typeName = getInput(prompt);
        String createTypeString = "create type " + typeName;
        if (typeToCreate.equals("d"))
            createTypeString += " as ";
        else
            createTypeString += " (";

        String commaAndSpace = ", ";
        boolean firstTime = true;
        while (true) {
            System.out.println("");
            prompt = "Enter an attribute name " + "(or nothing when finished) \nand hit Return: ";
            attributeName = getInput(prompt);
            if (firstTime) {
                if (attributeName.length() == 0) {
                    System.out.print("Need at least one attribute;");
                    System.out.println(" please try again");
                    continue;
                } else {
                    createTypeString += attributeName + " ";
                    firstTime = false;
                }
            } else if (attributeName.length() == 0) {
                break;
            } else {
                createTypeString += commaAndSpace + attributeName + " ";
            }

            String localTypeName = null;
            String paramString = "";
            while (true) {
                System.out.println("");
                System.out.println("LIST OF TYPES YOU MAY USE:  ");
                boolean firstPrinted = true;
                int length = 0;
                for (int i = 0; i < dataTypes.size(); i++) {
                    DataType dataType = (DataType) dataTypes.get(i);
                    if (!dataType.needsToBeSet()) {
                        if (!firstPrinted)
                            System.out.print(commaAndSpace);
                        else
                            firstPrinted = false;
                        System.out.print(dataType.getSQLType());
                        length += dataType.getSQLType().length();
                        if (length > 50) {
                            System.out.println("");
                            length = 0;
                            firstPrinted = true;
                        }
                    }
                }
                System.out.println("");

                int index;
                prompt = "Enter an attribute type " + "from the list and hit Return:  ";
                sqlType = getInput(prompt);
                for (index = 0; index < dataTypes.size(); index++) {
                    DataType dataType = (DataType) dataTypes.get(index);
                    if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
                        break;
                    }
                }

                localTypeName = null;
                paramString = "";
                if (index < dataTypes.size()) { // there was a match
                    String params;
                    DataType dataType = (DataType) dataTypes.get(index);
                    params = dataType.getParams();
                    localTypeName = dataType.getLocalType();
                    if (params != null) {
                        prompt = "Enter " + params + ":  ";
                        paramString = "(" + getInput(prompt) + ")";
                    }
                    break;
                } else { // use the name as given
                    prompt = "Are you sure?  " + "Enter 'y' or 'n' and hit Return:  ";
                    String check = getInput(prompt) + " ";
                    check = check.toLowerCase().substring(0, 1);
                    if (check.equals("n"))
                        continue;
                    else {
                        localTypeName = sqlType;
                        break;
                    }
                }
            }

            createTypeString += localTypeName + paramString;

            if (typeToCreate.equals("d"))
                break;
        }

        if (typeToCreate.equals("s"))
            createTypeString += ")";
        System.out.println("");
        System.out.print("Your CREATE TYPE statement as ");
        System.out.println("sent to your DBMS:  ");
        System.out.println(createTypeString);
        System.out.println("");

        stmt.executeUpdate(createTypeString);

        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:MainClass.java

public static void createDatabase() {
    String data = "jdbc:derby:presidents;create=true";
    try {//from w ww .j a v  a 2 s  .  co  m
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        Connection conn = DriverManager.getConnection(data);
        Statement st = conn.createStatement();
        int result = st.executeUpdate("CREATE TABLE contacts (dex INTEGER NOT NULL PRIMARY KEY "
                + "GENERATED ALWAYS AS identity (START WITH 1, INCREMENT BY 1), "
                + "name VARCHAR(40), address1 VARCHAR(40), address2 VARCHAR(40))");

        result = st.executeUpdate(
                "INSERT INTO contacts (name, address1, address2" + ") VALUES('J','Center', 1 , 'GA')");
        st.close();
    } catch (Exception e) {
        System.out.println("Error - " + e.toString());
    }
}

From source file:TestDB.java

 /**
 * Runs a test by creating a table, adding a value, showing the table contents, and removing the
 * table.//from   w w w  .j  a  v a  2  s .  c  om
 */
public static void runTest() throws SQLException, IOException
{
   Connection conn = getConnection();
   try
   {
      Statement stat = conn.createStatement();

      stat.executeUpdate("CREATE TABLE Greetings (Message CHAR(20))");
      stat.executeUpdate("INSERT INTO Greetings VALUES ('Hello, World!')");

      ResultSet result = stat.executeQuery("SELECT * FROM Greetings");
      if (result.next())
         System.out.println(result.getString(1));
      result.close();
      stat.executeUpdate("DROP TABLE Greetings");
   }
   finally
   {
      conn.close();
   }
}

From source file:Main.java

static void createTable(Connection conn) throws SQLException {
    Statement stat = null;
    stat = conn.createStatement();//from w ww  . java2s .c  om
    stat.executeUpdate("drop table if exists people;");
    stat.executeUpdate("create table people (name, occupation);");
    close(stat);
}

From source file:Main.java

public static void createBlobClobTables(Statement stmt) throws Exception {
    String Sql = "CREATE TABLE BlobClob(Id NUMBER(3), b BLOB, c CLOB)";

    try {/*w w  w.  ja v a2 s  .  co  m*/
        stmt.executeUpdate("DROP TABLE BlobClob");
    } catch (SQLException se) {
        if (se.getErrorCode() == 942)
            System.out.println("Error dropping BlobClob table:" + se.getMessage());
    }
    if (stmt.executeUpdate(Sql) == 0)
        System.out.println("BlobClob table created...");

}