Example usage for java.sql Connection close

List of usage examples for java.sql Connection close

Introduction

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

Prototype

void close() throws SQLException;

Source Link

Document

Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int,name varchar(30));");

    String sql = "INSERT INTO survey (id) VALUES(?)";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    ParameterMetaData pmd = pstmt.getParameterMetaData();

    int totalDigits = pmd.getPrecision(1);
    int digitsAfterDecimal = pmd.getScale(1);
    boolean b = pmd.isSigned(1);
    System.out.println("The first parameter ");
    System.out.println("    has precision " + totalDigits);
    System.out.println("    has scale " + digitsAfterDecimal);
    System.out.println("    may be a signed number " + b);

    int count = pmd.getParameterCount();
    System.out.println("count is " + count);

    for (int i = 1; i <= count; i++) {
        int type = pmd.getParameterType(i);
        String typeName = pmd.getParameterTypeName(i);
        System.out.println("Parameter " + i + ":");
        System.out.println("    type is " + type);
        System.out.println("    type name is " + typeName);
    }/* w  ww .  j a va  2s  .  c o  m*/

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Class.forName(DB_DRIVER);/*from  ww  w.  j  a  v a 2s  .  c  o m*/
    Connection dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);

    PreparedStatement preparedStatementInsert = null;
    PreparedStatement preparedStatementUpdate = null;

    String insertTableSQL = "INSERT INTO Person" + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
            + "(?,?,?,?)";

    String updateTableSQL = "UPDATE Person SET USERNAME =? " + "WHERE USER_ID = ?";

    java.util.Date today = new java.util.Date();
    dbConnection.setAutoCommit(false);

    preparedStatementInsert = dbConnection.prepareStatement(insertTableSQL);
    preparedStatementInsert.setInt(1, 9);
    preparedStatementInsert.setString(2, "101");
    preparedStatementInsert.setString(3, "system");
    preparedStatementInsert.setTimestamp(4, new java.sql.Timestamp(today.getTime()));
    preparedStatementInsert.executeUpdate();

    preparedStatementUpdate = dbConnection.prepareStatement(updateTableSQL);
    preparedStatementUpdate.setString(1, "new string");
    preparedStatementUpdate.setInt(2, 999);
    preparedStatementUpdate.executeUpdate();

    dbConnection.commit();
    dbConnection.close();
}

From source file:MainClass.java

public static void main(String[] args) {
    Connection connection = null;
    PreparedStatement statement = null;
    try {/* w w w  .j  ava2 s. c o m*/
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        String url = "jdbc:mysql://localhost/database";
        connection = DriverManager.getConnection(url, "username", "password");

        String sql = "UPDATE employees SET email = ? WHERE employee_id = ?";
        statement = connection.prepareStatement(sql);

        statement.setString(1, "a@a.com");
        statement.setLong(2, 1);
        statement.addBatch();

        statement.setString(1, "b@b.com");
        statement.setLong(2, 2);
        statement.addBatch();

        statement.setString(1, "c@c.com");
        statement.setLong(2, 3);
        statement.addBatch();

        statement.executeBatch();
    } 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:GetDateFromMySql.java

public static void main(String args[]) {
    ResultSet rs = null;//from   w w w  .ja  va  2 s .  c  om
    Connection conn = null;
    Statement stmt = null;
    try {
        conn = getMySQLConnection();
        stmt = conn.createStatement();
        rs = stmt.executeQuery("select timeCol, dateCol, dateTimeCol from dateTimeTable");
        while (rs.next()) {
            java.sql.Time dbSqlTime = rs.getTime(1);
            java.sql.Date dbSqlDate = rs.getDate(2);
            java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp(3);
            System.out.println("dbSqlTime=" + dbSqlTime);
            System.out.println("dbSqlDate=" + dbSqlDate);
            System.out.println("dbSqlTimestamp=" + dbSqlTimestamp);

            java.util.Date dbSqlTimeConverted = new java.util.Date(dbSqlTime.getTime());
            java.util.Date dbSqlDateConverted = new java.util.Date(dbSqlDate.getTime());
            System.out.println("in standard date");
            System.out.println(dbSqlTimeConverted);
            System.out.println(dbSqlDateConverted);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String deptName = "oldName";
    String newDeptName = "newName";

    ResultSet rs = null;//  ww  w  .  ja  v  a  2 s  .  c  o m
    Connection conn = null;
    PreparedStatement pstmt = null;
    PreparedStatement pstmt2 = null;
    try {
        conn = getConnection();
        // prepare query for getting a REF object and PrepareStatement object
        String refQuery = "select manager from dept_table where dept_name=?";
        pstmt = conn.prepareStatement(refQuery);
        pstmt.setString(1, deptName);
        rs = pstmt.executeQuery();
        java.sql.Ref ref = null;
        if (rs.next()) {
            ref = rs.getRef(1);
        }
        if (ref == null) {
            System.out.println("error: could not get a reference for manager.");
            System.exit(1);
        }
        String query = "INSERT INTO dept_table(dept_name, manager)values(?, ?)";
        pstmt2 = conn.prepareStatement(query);
        pstmt2.setString(1, newDeptName);
        pstmt2.setRef(2, ref);
        // execute query, and return number of rows created
        int rowCount = pstmt2.executeUpdate();
        System.out.println("rowCount=" + rowCount);
    } finally {
        pstmt.close();
        pstmt2.close();
        conn.close();
    }
}

From source file:Commons.dbcp.ManualPoolingDataSourceExample.java

public static void main(String[] args) {
    //// w w  w.  j  a v a2 s.  c  o  m
    // First we load the underlying JDBC driver.
    // You need this if you don't use the jdbc.drivers
    // system property.
    //
    System.out.println("Loading underlying JDBC driver.");
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("Done.");

    //
    // Then, we set up the PoolingDataSource.
    // Normally this would be handled auto-magically by
    // an external configuration, but in this example we'll
    // do it manually.
    //
    System.out.println("Setting up data source.");
    ////ee  DataSource dataSource = setupDataSource(args[0]);
    DataSource dataSource = setupDataSource("jdbc:oracle:thin:@10.1.1.184:1521:UTF8");
    System.out.println("Done.");

    //
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(args[1]);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        while (rset.next()) {
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            rset.close();
        } catch (Exception e) {
        }
        try {
            stmt.close();
        } catch (Exception e) {
        }
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int,myDate DATE );");
    String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";

    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
    pstmt.setString(1, "1");
    java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
    pstmt.setDate(2, sqlDate);/*from   w w  w .ja  v a  2  s.  com*/

    pstmt.executeUpdate();

    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    Calendar cal = Calendar.getInstance();

    // get the TimeZone for "America/Los_Angeles"
    TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
    cal.setTimeZone(tz);

    while (rs.next()) {
        // the JDBC driver will use the time zone information in
        // Calendar to calculate the date, with the result that
        // the variable dateCreated contains a java.sql.Date object
        // that is accurate for "America/Los_Angeles".
        java.sql.Date dateCreated = rs.getDate(2, cal);
        System.out.println(dateCreated);
    }

    rs.close();
    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String deptName = "oldName";
    String newDeptName = "newName";

    ResultSet rs = null;//from   w ww.j  av  a  2  s . c  om
    Connection conn = null;
    PreparedStatement pstmt = null;
    PreparedStatement pstmt2 = null;
    try {
        conn = getConnection();
        // prepare query for getting a REF object and PrepareStatement object
        String refQuery = "select manager from dept_table where dept_name=?";
        pstmt = conn.prepareStatement(refQuery);
        pstmt.setString(1, deptName);
        rs = pstmt.executeQuery();
        java.sql.Ref ref = null;
        if (rs.next()) {
            ref = rs.getRef("manager");
        }
        if (ref == null) {
            System.out.println("error: could not get a reference for manager.");
            System.exit(1);
        }
        String query = "INSERT INTO dept_table(dept_name, manager)values(?, ?)";
        pstmt2 = conn.prepareStatement(query);
        pstmt2.setString(1, newDeptName);
        pstmt2.setRef(2, ref);
        // execute query, and return number of rows created
        int rowCount = pstmt2.executeUpdate();
        System.out.println("rowCount=" + rowCount);
    } finally {
        pstmt.close();
        pstmt2.close();
        conn.close();
    }
}

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);");
    st.executeUpdate("create view surveyView as (select * from survey);");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    String query = "select * from survey where id > ? and name = ?";
    PreparedStatement pstmt = conn.prepareStatement(query);
    ParameterMetaData paramMetaData = pstmt.getParameterMetaData();
    if (paramMetaData == null) {
        System.out.println("db vendor does NOT support ParameterMetaData");
    } else {//  www  .j av  a 2  s  .com
        System.out.println("db vendor supports ParameterMetaData");
        int paramCount = paramMetaData.getParameterCount();
        System.out.println("paramCount=" + paramCount);
        System.out.println("-------------------");
        for (int param = 1; param <= paramCount; param++) {
            System.out.println("param number=" + param);
            System.out.println(paramMetaData.getPrecision(param));
        }
    }

    pstmt.close();
    conn.close();

}