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

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//w  w  w . j  a va 2s  .  co  m
    String createString;
    createString = "create table COFFEES " + "(COF_NAME varchar(32), " + "SUP_ID int, " + "PRICE float, "
            + "SALES int, " + "TOTAL int)";
    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();
        stmt.executeUpdate(createString);

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

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

From source file:CreateSuppliers.java

public static void main(String args[]) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;// w w w.  j av  a  2  s  . co m
    String createString;
    createString = "create table SUPPLIERS " + "(SUP_ID int, " + "SUP_NAME varchar(40), "
            + "STREET varchar(40), " + "CITY varchar(20), " + "STATE char(2), ZIP char(5))";

    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();
        stmt.executeUpdate(createString);

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

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

From source file:CreateStores.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*  ww w  .  ja v  a  2  s .c  o m*/
    String createTable;
    String createArray;
    createArray = "CREATE TYPE COF_ARRAY AS ARRAY(10) OF VARCHAR(40)";
    createTable = "CREATE TABLE STORES ( " + "STORE_NO INTEGER, LOCATION ADDRESS, "
            + "COF_TYPES COF_ARRAY, MGR REF MANAGER )";
    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();

        stmt.executeUpdate(createArray);
        stmt.executeUpdate(createTable);

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

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

From source file:PrimaryKeysSuppliers.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//  ww w  .j  a v  a2  s .c  o m
    String createString = "create table SUPPLIERSPK " + "(SUP_ID INTEGER NOT NULL, " + "SUP_NAME VARCHAR(40), "
            + "STREET VARCHAR(40), " + "CITY VARCHAR(20), " + "STATE CHAR(2), " + "ZIP CHAR(5), "
            + "primary key(SUP_ID))";
    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();
        stmt.executeUpdate(createString);

        DatabaseMetaData dbmd = con.getMetaData();

        ResultSet rs = dbmd.getPrimaryKeys(null, null, "SUPPLIERSPK");
        while (rs.next()) {
            String name = rs.getString("TABLE_NAME");
            String columnName = rs.getString("COLUMN_NAME");
            String keySeq = rs.getString("KEY_SEQ");
            String pkName = rs.getString("PK_NAME");
            System.out.println("table name :  " + name);
            System.out.println("column name:  " + columnName);
            System.out.println("sequence in key:  " + keySeq);
            System.out.println("primary key name:  " + pkName);
            System.out.println("");
        }

        rs.close();
        con.close();

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

From source file:ForeignKeysCoffees.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//from w w w .  j  a v  a2s.c  om
    String createString = "create table COFFEESFK " + "(COF_NAME varchar(32) NOT NULL, " + "SUP_ID int, "
            + "PRICE float, " + "SALES int, " + "TOTAL int, " + "primary key(COF_NAME), "
            + "foreign key(SUP_ID) references SUPPLIERSPK)";
    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();
        stmt.executeUpdate(createString);

        DatabaseMetaData dbmd = con.getMetaData();

        ResultSet rs = dbmd.getImportedKeys(null, null, "COFFEESFK");
        while (rs.next()) {
            String pkTable = rs.getString("PKTABLE_NAME");
            String pkColName = rs.getString("PKCOLUMN_NAME");
            String fkTable = rs.getString("FKTABLE_NAME");
            String fkColName = rs.getString("FKCOLUMN_NAME");
            short updateRule = rs.getShort("UPDATE_RULE");
            short deleteRule = rs.getShort("DELETE_RULE");
            System.out.println("primary key table name :  " + pkTable);
            System.out.print("primary key column name :  ");
            System.out.println(pkColName);
            System.out.println("foreign key table name :  " + fkTable);
            System.out.print("foreign key column name :  ");
            System.out.println(fkColName);
            System.out.println("update rule:  " + updateRule);
            System.out.println("delete rule:  " + deleteRule);
            System.out.println("");
        }

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

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

From source file:MainClass.java

public static void main(String[] args) {
    Connection connection = null;
    Statement statement = null;
    try {/*from w  w w.  j a  v a2 s.  c om*/
        Class.forName("org.hsqldb.jdbcDriver").newInstance();
        String url = "jdbc:hsqldb:hsqldb\\demoDatabase";
        connection = DriverManager.getConnection(url, "username", "password");
        connection.setAutoCommit(false);

        statement = connection.createStatement();

        String update1 = "UPDATE employees SET email = 'a@b.com' WHERE email = 'a@a.com'";
        statement.executeUpdate(update1);
        Savepoint savepoint1 = connection.setSavepoint("savepoint1");

        String update2 = "UPDATE employees SET email = 'b@b.com' WHERE email = 'b@c.com'";
        statement.executeUpdate(update2);
        Savepoint savepoint2 = connection.setSavepoint("savepoint2");

        String update3 = "UPDATE employees SET email = 'c@c.com' WHERE email = 'c@d.com'";
        statement.executeUpdate(update3);
        Savepoint savepoint3 = connection.setSavepoint("savepoint3");

        String update4 = "UPDATE employees SET email = 'd@d.com' WHERE email = 'd@e.com'";
        statement.executeUpdate(update4);
        Savepoint savepoint4 = connection.setSavepoint("savepoint4");

        String update5 = "UPDATE employees SET email = 'e@e.com' WHERE email = 'e@f.com'";
        statement.executeUpdate(update5);
        Savepoint savepoint5 = connection.setSavepoint("savepoint5");

        connection.rollback(savepoint3);
        connection.commit();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        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 = null;//  w w w  .  j a  va  2s  . c om
    Statement stmt = null;

    Class.forName(JDBC_DRIVER);
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    System.out.println("Deleting database...");
    stmt = conn.createStatement();

    conn = DriverManager.getConnection(DB_URL, USER, PASS);

    stmt = conn.createStatement();

    String sql = "CREATE TABLE Person" + "(id INTEGER not NULL, " + " firstName VARCHAR(50), "
            + " lastName VARCHAR(50), " + " age INTEGER, " + " PRIMARY KEY ( id ))";

    stmt.executeUpdate(sql);
    System.out.println("Created table in given database...");
    stmt.close();
    conn.close();
}

From source file:org.ipinfodb.IpInfoDbClient.java

public static void main(String[] args) throws IOException {
    if (args.length < 3 || args.length > 4) {
        System.out.println("Usage: org.ipinfodb.IpInfoDbClient MODE API_KEY [IP_ADDRESS]\n"
                + "MODE can be either 'ip-country' or 'ip-city'.\n"
                + "If you don't have an API_KEY yet, you can get one for free by registering at http://www.ipinfodb.com/register.php.");
        return;//  w w  w  .j  a  v  a2  s  . c o  m
    }

    //Code for Reading the multiple ip addresses from a given txt file.
    File inputLogFilePath = new File(args[1]);
    FileReader fr = new FileReader(inputLogFilePath);
    BufferedReader br = new BufferedReader(fr);
    String logLine;
    /*File outputFile=new File("C:/Users/Intelligrape/Desktop/New_Sample_29042014.txt");
    // if file doesnt exists, then create it
       if (!outputFile.exists()) {
          outputFile.createNewFile();
       }
             
    FileWriter fw = new FileWriter(outputFile,true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write("S.no, IPAddress, Country, Region, City, Zipcode");
    bw.newLine();*/

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

    String url_db = "jdbc:mysql://mysqldb.c7zitrf2gguq.us-east-1.rds.amazonaws.com/matse?user=shagun&password=shagun001";

    Connection con = null;

    int insertCounter = 0;
    int count = 1;

    while ((logLine = br.readLine()) != null) {

        String mode = args[2];
        String apiKey = args[3];
        String url = "http://api.ipinfodb.com/v3/" + mode + "/?format=json&key=" + apiKey;
        String[] split = logLine.split(",");
        String ip = split[3];
        url += "&ip=" + ip;

        try {
            HttpGet request = new HttpGet(url);
            HttpResponse response = HTTP_CLIENT.execute(request, new BasicHttpContext());
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new RuntimeException("IpInfoDb response is " + response.getStatusLine());
            }

            String responseBody = EntityUtils.toString(response.getEntity());
            IpCityResponse ipCityResponse = MAPPER.readValue(responseBody, IpCityResponse.class);
            if ("OK".equals(ipCityResponse.getStatusCode())) {
                //System.out.print(count+", "+ip+", "+ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", " + ipCityResponse.getCityName() + ", " + ipCityResponse.zipCode+ ", " + ipCityResponse.countryName + ", " + ipCityResponse.latitude + ", " + ipCityResponse.longitude + ", " + ipCityResponse.timeZone);
                //bw.write(count+", "+ip+", "+ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", " + ipCityResponse.getCityName() + ", " + ipCityResponse.zipCode + ", " + ipCityResponse.countryName + ", " + ipCityResponse.latitude + ", " + ipCityResponse.longitude + ", " + ipCityResponse.timeZone);

                try {
                    con = DriverManager.getConnection(url_db);
                    //System.out.println("Connected successfully"); 
                    Statement stmt = con.createStatement();
                    //System.out.println(logLine);
                    //System.out.println(split.length);
                    int result = stmt.executeUpdate("INSERT INTO LOGDATA1 VALUES('" + split[0] + "','"
                            + split[1].trim() + "','" + split[2] + "','" + split[3] + "','" + split[4] + "','"
                            + ipCityResponse.statusCode + "','" + ipCityResponse.countryCode + "','"
                            + ipCityResponse.countryName + "','" + ipCityResponse.regionName + "','"
                            + ipCityResponse.cityName + "','" + ipCityResponse.zipCode + "','"
                            + ipCityResponse.latitude + "','" + ipCityResponse.longitude + "','"
                            + ipCityResponse.timeZone + "')");
                    ++insertCounter;
                    con.close();
                    System.out.println(insertCounter);
                } catch (SQLException e) {
                    System.out.println("something wrong in the connection string: " + e);
                }

            } else {
                System.out.print("API status message is '" + ipCityResponse.getStatusMessage() + "'");
            }
        } finally {

            //HTTP_CLIENT.getConnectionManager().shutdown();

        }
        ++count;

    }
    HTTP_CLIENT.getConnectionManager().shutdown();

}

From source file:InsertSuppliers.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*from  w ww. ja  v  a  2 s  .com*/
    Statement stmt;
    String query = "select SUP_NAME, SUP_ID from SUPPLIERS";

    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();

        stmt.executeUpdate("insert into SUPPLIERS " + "values(49, 'Superior Coffee', '1 Party Place', "
                + "'Mendocino', 'CA', '95460')");

        stmt.executeUpdate("insert into SUPPLIERS " + "values(101, 'Acme, Inc.', '99 Market Street', "
                + "'Groundsville', 'CA', '95199')");

        stmt.executeUpdate("insert into SUPPLIERS " + "values(150, 'The High Ground', '100 Coffee Lane', "
                + "'Meadows', 'CA', '93966')");

        ResultSet rs = stmt.executeQuery(query);

        System.out.println("Suppliers and their ID Numbers:");
        while (rs.next()) {
            String s = rs.getString("SUP_NAME");
            int n = rs.getInt("SUP_ID");
            System.out.println(s + "   " + n);
        }

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

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

From source file:InsertCoffees.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//from w w  w  .  j  a  v  a2  s  . c  o m
    Statement stmt;
    String query = "select COF_NAME, PRICE from COFFEES";

    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();

        stmt.executeUpdate("insert into COFFEES " + "values('Colombian', 00101, 7.99, 0, 0)");

        stmt.executeUpdate("insert into COFFEES " + "values('French_Roast', 00049, 8.99, 0, 0)");

        stmt.executeUpdate("insert into COFFEES " + "values('Espresso', 00150, 9.99, 0, 0)");

        stmt.executeUpdate("insert into COFFEES " + "values('Colombian_Decaf', 00101, 8.99, 0, 0)");

        stmt.executeUpdate("insert into COFFEES " + "values('French_Roast_Decaf', 00049, 9.99, 0, 0)");

        ResultSet rs = stmt.executeQuery(query);

        System.out.println("Coffee Break Coffees and Prices:");
        while (rs.next()) {
            String s = rs.getString("COF_NAME");
            float f = rs.getFloat("PRICE");
            System.out.println(s + "   " + f);
        }

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

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