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

public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;//from  ww  w  . j ava2s .  com
    ResultSet rs = null;
    try {
        conn = getConnection();
        String query = "select id, name from employees";
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery(query);
        // extract data from the ResultSet scroll from top
        while (rs.next()) {
            String id = rs.getString(1);
            String name = rs.getString(2);
            System.out.println("id=" + id + "  name=" + name);
        }
        // scroll from the bottom
        rs.afterLast();
        while (rs.previous()) {
            String id = rs.getString(1);
            String name = rs.getString(2);
            System.out.println("id=" + id + "  name=" + name);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // release database resources
        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 {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    st = conn.createStatement();/*ww w  . j  a va2s  .co  m*/
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    ResultSetMetaData rsMetaData = rs.getMetaData();

    int numberOfColumns = rsMetaData.getColumnCount();
    System.out.println("resultSet MetaData column Count=" + numberOfColumns);

    for (int i = 1; i <= numberOfColumns; i++) {
        System.out.println("column MetaData ");
        System.out.println("column number " + i);
        // indicates the designated column's normal maximum width in
        // characters
        System.out.println(rsMetaData.getColumnDisplaySize(i));
        // gets the designated column's suggested title
        // for use in printouts and displays.
    }

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

From source file:DemoPreparedStatementSetBinaryStream.java

public static void main(String[] args) throws Exception {
    String smallFileName = "smallFileName.dat";
    String largeFileName = "largeFileName.dat";
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {/*from   w w  w .  j a  v  a 2 s. c  om*/
        conn = getConnection();
        File smallFile = new File(smallFileName);
        int smallFileLength = (int) smallFile.length();
        InputStream smallStream = (InputStream) new FileInputStream(smallFile);
        File largeFile = new File(largeFileName);
        int largeFileLength = (int) largeFile.length();
        InputStream largeStream = (InputStream) new FileInputStream(largeFile);

        String query = "insert into binary_table(id, raw_column, long_raw_column) values(?, ?, ?)";

        conn.setAutoCommit(false);
        pstmt = conn.prepareStatement(query);
        pstmt.setString(1, "0001");
        pstmt.setBinaryStream(2, smallStream, smallFileLength);
        pstmt.setBinaryStream(3, largeStream, largeFileLength);

        // execute query, and return number of rows created
        int rowCount = pstmt.executeUpdate();
        System.out.println("rowCount=" + rowCount);
        conn.commit();
    } finally {
        pstmt.close();
        conn.close();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    try {/*from   w  ww .j  a v a2  s . c  om*/
        String url = "jdbc:odbc:yourdatabasename";
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String user = "guest";
        String password = "guest";

        FileInputStream fis = new FileInputStream("sometextfile.txt");

        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        Statement createTable = connection.createStatement();
        createTable.executeUpdate("CREATE TABLE source_code (name char(20), source LONGTEXT)");
        String ins = "INSERT INTO source_code VALUES(?,?)";
        PreparedStatement statement = connection.prepareStatement(ins);

        statement.setString(1, "TryInputStream2");
        statement.setAsciiStream(2, fis, fis.available());

        int rowsUpdated = statement.executeUpdate();
        System.out.println("Rows affected: " + rowsUpdated);
        Statement getCode = connection.createStatement();
        ResultSet theCode = getCode.executeQuery("SELECT name,source FROM source_code");
        BufferedReader reader = null;
        String input = null;

        while (theCode.next()) {
            reader = new BufferedReader(new InputStreamReader(theCode.getAsciiStream(2)));
            while ((input = reader.readLine()) != null) {
                System.out.println(input);
            }
        }
        connection.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:DemoPreparedStatementSetCharacterStream.java

public static void main(String[] args) throws Exception {
    String fileName = "charDataFile.txt";
    Reader fileReader = null;/*from www.ja va2s  .  c o  m*/
    long fileLength = 0;
    Connection conn = null;
    PreparedStatement pstmt = null;

    try {
        File file = new File(fileName);
        fileLength = file.length();
        fileReader = (Reader) new BufferedReader(new FileReader(file));
        System.out.println("fileName=" + fileName);
        System.out.println("fileLength=" + fileLength);

        conn = getConnection();
        // begin transaction
        conn.setAutoCommit(false);
        // prepare SQL query for inserting a new row using SetCharacterStream()
        String query = "insert into char_stream_table (id, char_stream_column) values(?, ?)";
        // create PrepareStatement object
        pstmt = conn.prepareStatement(query);
        pstmt.setString(1, fileName);
        pstmt.setCharacterStream(2, fileReader, (int) fileLength);
        // execute query, and return number of rows created
        int rowCount = pstmt.executeUpdate();
        System.out.println("rowCount=" + rowCount);
        // end transaction
        conn.commit();
    } finally {
        pstmt.close();
        conn.close();
    }
}

From source file:DemoResultSetOracle.java

public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;/*  w ww  .j  av a2s.  co  m*/
    ResultSet rs = null;
    try {
        conn = getConnection();
        System.out.println("conn=" + conn);
        // prepare query
        String query = "select id, name, age from employees";
        // create a statement
        stmt = conn.createStatement();
        // execute query and return result as a ResultSet
        rs = stmt.executeQuery(query);
        // extract data from the ResultSet
        while (rs.next()) {
            String id = rs.getString(1);
            String name = rs.getString(2);
            int age = rs.getInt(3);
            System.out.println("id=" + id);
            System.out.println("name=" + name);
            System.out.println("age=" + age);
            System.out.println("---------------");
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        // release database resources
        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 {
    try {//from  w ww  .  ja  va 2 s  .co m
        String url = "jdbc:odbc:yourdatabasename";
        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        String user = "guest";
        String password = "guest";

        FileInputStream fis = new FileInputStream("sometextfile.txt");

        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);
        Statement createTable = connection.createStatement();
        createTable.executeUpdate("CREATE TABLE source_code (name char(20), source LONGTEXT)");
        String ins = "INSERT INTO source_code VALUES(?,?)";
        PreparedStatement statement = connection.prepareStatement(ins);

        statement.setString(1, "TryInputStream2");
        statement.setAsciiStream(2, fis, fis.available());

        int rowsUpdated = statement.executeUpdate();
        System.out.println("Rows affected: " + rowsUpdated);
        Statement getCode = connection.createStatement();
        ResultSet theCode = getCode.executeQuery("SELECT name,source FROM source_code");
        BufferedReader reader = null;
        String input = null;

        while (theCode.next()) {
            reader = new BufferedReader(new InputStreamReader(theCode.getAsciiStream("source")));
            while ((input = reader.readLine()) != null) {
                System.out.println(input);
            }
        }
        connection.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

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;//from   w w  w  .  j  a v  a  2  s.com
    try {
        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:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = null;
    PreparedStatement pstmt = null;
    Statement stmt = null;/*  w  ww . ja v  a2s.  com*/
    ResultSet rs = null;
    Class.forName(JDBC_DRIVER);
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    stmt = conn.createStatement();
    createXMLTable(stmt);
    File f = new File("build.xml");
    long fileLength = f.length();
    FileInputStream fis = new FileInputStream(f);
    String SQL = "INSERT INTO XML_Data VALUES (?,?)";
    pstmt = conn.prepareStatement(SQL);
    pstmt.setInt(1, 100);
    pstmt.setAsciiStream(2, fis, (int) fileLength);
    pstmt.execute();
    fis.close();
    SQL = "SELECT Data FROM XML_Data WHERE id=100";
    rs = stmt.executeQuery(SQL);
    if (rs.next()) {
        InputStream xmlInputStream = rs.getAsciiStream(1);
        int c;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((c = xmlInputStream.read()) != -1)
            bos.write(c);
        System.out.println(bos.toString());
    }
    rs.close();
    stmt.close();
    pstmt.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";

    Connection con;
    Statement stmt;//from  w ww.  j ava  2  s.co  m
    ResultSet rs;

    try {
        Class.forName(driver);
        con = DriverManager.getConnection("jdbc:odbc:databaseName", "student", "student");
        // Start a transaction
        con.setAutoCommit(false);

        stmt = con.createStatement();
        stmt.addBatch("UPDATE EMP SET JOB = 1");

        // Submit the batch of commands for this statement to the database
        stmt.executeBatch();

        // Commit the transaction
        con.commit();

        // Close the existing to be safe before opening a new one
        stmt.close();

        // Print out the Employees
        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT * FROM EMP");
        // Loop through and print the employee number, job, and hiredate
        while (rs.next()) {
            int id = rs.getInt("EMPNO");
            int job = rs.getInt("JOB");
            String hireDate = rs.getString("HIREDATE");

            System.out.println(id + ":" + job + ":" + hireDate);
        }
        con.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}