Example usage for java.sql Connection createStatement

List of usage examples for java.sql Connection createStatement

Introduction

In this page you can find the example usage for java.sql Connection createStatement.

Prototype

Statement createStatement() throws SQLException;

Source Link

Document

Creates a Statement object for sending SQL statements to the database.

Usage

From source file:MainClass.java

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

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

public static void main(String args[]) {

    try {/*from www . j a v a  2 s. c  o  m*/
        Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    } catch (ClassNotFoundException e) {
        System.out.println("Oops! Can't find class oracle.jdbc.driver.OracleDriver");
        System.exit(1);
    } catch (IllegalAccessException e) {
        System.out.println("Uh Oh! You can't load oracle.jdbc.driver.OracleDriver");
        System.exit(2);
    } catch (InstantiationException e) {
        System.out.println("Geez! Can't instantiate oracle.jdbc.driver.OracleDriver");
        System.exit(3);
    }

    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;
    try {
        conn = DriverManager.getConnection("jdbc:oracle:thin:@dssw2k01:1521:orcl", "scott", "tiger");

        stmt = conn.createStatement();
        rset = stmt.executeQuery("select 'Hello '||USER||'!' result from dual");
        while (rset.next())
            System.out.println(rset.getString(1));
        rset.close();
        rset = null;
        stmt.close();
        stmt = null;
        conn.close();
        conn = null;
    } catch (SQLException e) {
        System.out.println("Darn! A SQL error: " + e.getMessage());
    } finally {
        if (rset != null)
            try {
                rset.close();
            } catch (SQLException ignore) {
            }
        if (stmt != null)
            try {
                stmt.close();
            } catch (SQLException ignore) {
            }
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};"
            + "Dbq=C:\\Users\\Public\\uls\\ulsTest.mdb;" + "SystemDB=C:\\Users\\Public\\uls\\Security.mdw;"
            + "Uid=Gord;" + "Pwd=obfuscated;" + "ExtendedAnsiSQL=1;");
    Statement s = conn.createStatement();
    s.execute("CREATE USER Tim pwd");
    System.out.println("User 'Tim' created.");
    s.execute("DROP USER Tim");
    System.out.println("User 'Tim' dropped.");
    s.close();//w w  w  .j a va  2s.com
    conn.close();
}

From source file:TypeMapDemo.java

public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {

    Properties p = new Properties();
    p.load(new FileInputStream("db.properties"));
    Class c = Class.forName(p.getProperty("db.driver"));
    System.out.println("Loaded driverClass " + c.getName());

    Connection con = DriverManager.getConnection(p.getProperty("db.url"), "student", "student");
    System.out.println("Got Connection " + con);

    Statement s = con.createStatement();
    int ret;/*from w w w  .  j a v  a 2s.  c  o m*/
    try {
        s.executeUpdate("drop table MR");
        s.executeUpdate("drop type MUSICRECORDING");
    } catch (SQLException andDoNothingWithIt) {
        // Should use "if defined" but not sure it works for UDTs...
    }
    ret = s.executeUpdate("create type MUSICRECORDING as object (" + "   id integer," + "   title varchar(20), "
            + "   artist varchar(20) " + ")");
    System.out.println("Created TYPE! Ret=" + ret);

    ret = s.executeUpdate("create table MR of MUSICRECORDING");
    System.out.println("Created TABLE! Ret=" + ret);

    int nRows = s.executeUpdate("insert into MR values(123, 'Greatest Hits', 'Ian')");
    System.out.println("inserted " + nRows + " rows");

    // Put the data class into the connection's Type Map
    // If the data class were not an inner class,
    // this would likely be done with Class.forName(...);
    Map map = con.getTypeMap();
    map.put("MUSICRECORDING", MusicRecording.class);
    con.setTypeMap(map);

    ResultSet rs = s.executeQuery("select * from MR where id = 123");
    //"select musicrecording(id,artist,title) from mr");
    rs.next();
    for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
        Object o = rs.getObject(i);
        System.out.print(o + "(Type " + o.getClass().getName() + ")\t");
    }
    System.out.println();
}

From source file:TestOCINet8App.java

public static void main(String args[]) throws ClassNotFoundException, SQLException {

    Class.forName("oracle.jdbc.driver.OracleDriver");
    // or you can use:
    //  DriverManager.registerDriver(
    //   new oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection("jdbc:oracle:oci8:@(DESCRIPTION = "
            + "(ADDRESS_LIST = (ADDRESS = " + "(PROTOCOL = TCP)(HOST = dssw2k01)(PORT = 1521)))"
            + "(CONNECT_DATA = (SERVICE_NAME = dssw2k01)))", "scott", "tiger");

    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery("select 'Hello OCI driver tester '||USER||'!' result from dual");
    while (rset.next())
        System.out.println(rset.getString(1));
    rset.close();//from w w w .  jav a 2 s.  c  o m
    stmt.close();
    conn.close();
}

From source file:com.kylinolap.query.QueryCli.java

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

    Options options = new Options();
    options.addOption(OPTION_METADATA);/*w  w w .j  a v a 2s  .c o  m*/
    options.addOption(OPTION_SQL);

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = parser.parse(options, args);
    KylinConfig config = KylinConfig
            .createInstanceFromUri(commandLine.getOptionValue(OPTION_METADATA.getOpt()));
    String sql = commandLine.getOptionValue(OPTION_SQL.getOpt());

    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    File olapTmp = OLAPSchemaFactory.createTempOLAPJson(null, config);

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = DriverManager.getConnection("jdbc:optiq:model=" + olapTmp.getAbsolutePath());

        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);
        int n = 0;
        ResultSetMetaData meta = rs.getMetaData();
        while (rs.next()) {
            n++;
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                System.out.println(n + " - " + meta.getColumnLabel(i) + ":\t" + rs.getObject(i));
            }
        }
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }

}

From source file:com.hangum.tadpole.engine.procedure.OracleProcedure.java

/**
 * @param args/*from w  ww.j  a  va2s .com*/
 */
public static void main(String[] args) {

    String strQuery = "CREATE OR REPLACE PROCEDURE procOneINOUTParameter(genericParam IN OUT VARCHAR2) "
            + " IS " + "      BEGIN "
            + "        genericParam := 'Hello World INOUT parameter ' || genericParam; " + "      END;";

    Connection conn = null;
    Statement stmt = null;
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.32.128:1521:XE", "HR", "tadpole");

        stmt = conn.createStatement();
        int code = stmt.executeUpdate(strQuery);
        System.out.println("[result]" + code);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar, age int);");
    st.executeUpdate("insert into survey (id,name,age ) values (1,'nameValue', 10)");
    st.executeUpdate("insert into survey (id,name,age ) values (2,'anotherValue', 100)");

    FilteredRowSet frs = new FilteredRowSetImpl();
    frs.setUsername("sa");
    frs.setPassword("");
    frs.setUrl("jdbc:hsqldb:data/tutorial");
    frs.setCommand("SELECT id, name, age FROM survey");
    frs.execute();// www. ja  v  a2  s  . c o m

    System.out.println("--- Unfiltered RowSet: ---");
    while (frs.next()) {
        System.out.println(frs.getRow() + " - " + frs.getString("id") + ":" + frs.getString("name") + ":"
                + frs.getInt("age"));
    }
    // create a filter that restricts entries in
    // the age column to be between 7 and 10
    AgeFilter filter = new AgeFilter(7, 10, 3);

    // set the filter.
    frs.beforeFirst();
    frs.setFilter(filter);

    // go to the beginning of the Rowset
    System.out.println("--- Filtered RowSet: ---");

    // show filtered data
    while (frs.next()) {
        System.out.println(frs.getRow() + " - " + frs.getString("id") + ":" + frs.getString("name") + ":"
                + frs.getInt("age"));
    }

    System.out.println("--- Try to insert new records ---");

    // Try to add an employee with age = 90 (allowed by filter)
    frs.moveToInsertRow();
    frs.updateString(1, "999");
    frs.updateString(2, "Andre");
    frs.updateInt(3, 90);
    frs.insertRow();
    frs.moveToCurrentRow();
    frs.acceptChanges();

    // try to add an survey with age = 65 (not allowed by filter)
    frs.moveToInsertRow();
    frs.updateString(1, "123");
    frs.updateString(2, "Jeff");
    frs.updateInt(3, 65);
    frs.insertRow();
    frs.moveToCurrentRow();
    frs.acceptChanges();

    // scroll to first row of rowset
    frs.beforeFirst();
    // display rows in FilteredRowset
    System.out.println("FilteredRowSet after trying to insert Jeff (age 65) and Andre (age 90):");
    while (frs.next()) {
        System.out.println(frs.getRow() + " - " + frs.getString("id") + ":" + frs.getString("name") + ":"
                + frs.getInt("age"));
    }

    frs.close();
    st.close();
    frs.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    System.out.println("Inserting values in  database table!");
    Connection con = null;
    String url = "jdbc:jtds:sqlserver://127.0.0.1:1433/Example";
    String username = "sa";
    String password = "";
    String driver = "net.sourceforge.jtds.jdbc.Driver";
    Class.forName(driver);//from   w ww . j  a v a 2s.com
    con = DriverManager.getConnection(url, username, password);
    Statement st = con.createStatement();
    int val = st.executeUpdate("insert into dbo.Company " + "values('abc', 2)");
    System.out.println("1 row affected");
}

From source file:MainClass.java

public static void main(String[] args) {
    Connection connection = null;
    Statement statement = null;/*from w  w  w  .  j a  v a 2  s  .  c  o  m*/
    try {
        Class.forName("org.gjt.mm.mysql.Driver").newInstance();
        String url = "jdbc:mysql://localhost/mysql";
        connection = DriverManager.getConnection(url, "username", "password");
        statement = connection.createStatement();
        String hrappSQL = "CREATE DATABASE hrapp";
        statement.executeUpdate(hrappSQL);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
            }
        }
    }
}