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 stmt = conn.createStatement();

    stmt.executeUpdate("create table survey (id int, id2 tinyint, id3 smallint, id4 bigint, id5 real);");

    String sql = "INSERT INTO survey (id2,id3,id4,id5) VALUES(?,?,?,?)";
    PreparedStatement pstmt = conn.prepareStatement(sql);

    byte b = 1;//from www  .  j a v  a2 s. com
    short s = 2;
    pstmt.setByte(1, b);
    pstmt.setShort(2, s);
    pstmt.setInt(3, 3);
    pstmt.setLong(4, 4L);
    pstmt.executeUpdate();

    ResultSet rs = stmt.executeQuery("SELECT * FROM survey");
    while (rs.next()) {
        System.out.println(rs.getString(2));
    }

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

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "");

    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = statement.executeQuery("SELECT * FROM products");
    resultSet.afterLast();/*from   w  w  w .  ja  va 2s . c o  m*/
    while (resultSet.previous()) {
        String productCode = resultSet.getString("product_code");
        String productName = resultSet.getString("product_name");
        int quantity = resultSet.getInt("quantity");
        double price = resultSet.getDouble("price");

        System.out.println(productCode + "\t" + productName + "\t" + quantity + "\t" + price);
    }
    connection.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(url, username, password);

    String sql = "SELECT name, description, image FROM pictures ";
    PreparedStatement stmt = conn.prepareStatement(sql);
    ResultSet resultSet = stmt.executeQuery();
    while (resultSet.next()) {
        String name = resultSet.getString(1);
        String description = resultSet.getString(2);
        File image = new File("D:\\java.gif");
        FileOutputStream fos = new FileOutputStream(image);

        byte[] buffer = new byte[1];
        InputStream is = resultSet.getBinaryStream(3);
        while (is.read(buffer) > 0) {
            fos.write(buffer);//w ww  .  j  a v a 2s .  c om
        }
        fos.close();
    }
    conn.close();
}

From source file:GetColumnNamesFromResultSet_Oracle.java

public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;/*from   ww w.  j a v a2 s .  c  o m*/
    ResultSet rs = null;
    try {
        conn = getConnection();
        // 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);
        // get the column names from the ResultSet
        getColumnNames(rs);
    } 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 = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
    st = conn.createStatement();/*from  ww  w  .  j  a va  2 s .  c  o m*/
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    rs = st.executeQuery("SELECT COUNT(*) FROM survey");
    // get the number of rows from the result set
    rs.next();
    int rowCount = rs.getInt(1);
    System.out.println(rowCount);

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

}

From source file:Connect.java

public static void main(String[] av) {
    String dbURL = "jdbc:odbc:Companies";
    try {/*from  w  ww  . ja  va  2 s.  c  o  m*/
        // Load the jdbc-odbc bridge driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        // Enable logging
        DriverManager.setLogWriter(new PrintWriter((System.err)));

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection(dbURL, "ian", ""); // user,
        // passwd

        // If a SQLWarning object is available, print its
        // warning(s). There may be multiple warnings chained.

        SQLWarning warn = conn.getWarnings();
        while (warn != null) {
            System.out.println("SQLState: " + warn.getSQLState());
            System.out.println("Message:  " + warn.getMessage());
            System.out.println("Vendor:   " + warn.getErrorCode());
            System.out.println("");
            warn = warn.getNextWarning();
        }

        // Do something with the connection here...

        conn.close(); // All done with that DB connection

    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException e) {
        System.out.println("Database access failed " + e);
    }
}

From source file:com.kaidad.utilities.MBTilesBase64Converter.java

public static void main(String... args) throws SQLException {
    if (args.length != 1) {
        System.out.println("Usage: MBTilesBase64Converter /path/to/file.mbtiles");
        System.exit(1);/*from w  w  w. java  2 s  . c  o m*/
    }
    Connection c = null;
    try {
        c = connectToDb(args[0]);
        //        Statement st = c.createStatement();
        //        ResultSet rs = st.executeQuery("SELECT type, name, tbl_name FROM sqlite_master WHERE type='table'");
        //        while(rs.next()) {
        //            System.out.println("type: " + rs.getString(1) + ", name: " + rs.getString(2) + ", tbl_name: " + rs.getString(3));
        //        }
        JdbcTemplate template = new JdbcTemplate(new SingleConnectionDataSource(c, true));
        executeConversion(template);
        c.commit();
    } finally {
        if (c != null) {
            c.close();
        }
    }
}

From source file:com.linecorp.platform.channel.sample.Main.java

public static void main(String[] args) {

    BusinessConnect bc = new BusinessConnect();

    /**/* ww w.j  a  v a  2  s . c  o m*/
     * Prepare the required channel secret and access token
     */
    String channelSecret = System.getenv("CHANNEL_SECRET");
    String channelAccessToken = System.getenv("CHANNEL_ACCESS_TOKEN");
    if (channelSecret == null || channelSecret.isEmpty() || channelAccessToken == null
            || channelAccessToken.isEmpty()) {
        System.err.println("Error! Environment variable CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN not defined.");
        return;
    }

    port(Integer.valueOf(System.getenv("PORT")));
    staticFileLocation("/public");

    /**
     * Define the callback url path
     */
    post("/events", (request, response) -> {
        String requestBody = request.body();

        /**
         * Verify whether the channel signature is valid or not
         */
        String channelSignature = request.headers("X-LINE-CHANNELSIGNATURE");
        if (channelSignature == null || channelSignature.isEmpty()) {
            response.status(400);
            return "Please provide valid channel signature and try again.";
        }
        if (!bc.validateBCRequest(requestBody, channelSecret, channelSignature)) {
            response.status(401);
            return "Invalid channel signature.";
        }

        /**
         * Parse the http request body
         */
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        EventList events;
        try {
            events = objectMapper.readValue(requestBody, EventList.class);
        } catch (IOException e) {
            response.status(400);
            return "Invalid request body.";
        }

        ApiHttpClient apiHttpClient = new ApiHttpClient(channelAccessToken);

        /**
         * Process the incoming messages/operations one by one
         */
        List<String> toUsers;
        for (Event event : events.getResult()) {
            switch (event.getEventType()) {
            case Constants.EventType.MESSAGE:
                toUsers = new ArrayList<>();
                toUsers.add(event.getContent().getFrom());

                // @TODO: We strongly suggest you should modify this to process the incoming message/operation async
                bc.sendTextMessage(toUsers, "You said: " + event.getContent().getText(), apiHttpClient);
                break;
            case Constants.EventType.OPERATION:
                if (event.getContent().getOpType() == Constants.OperationType.ADDED_AS_FRIEND) {
                    String newFriend = event.getContent().getParams().get(0);
                    Profile profile = bc.getProfile(newFriend, apiHttpClient);
                    String displayName = profile == null ? "Unknown" : profile.getDisplayName();
                    toUsers = new ArrayList<>();
                    toUsers.add(newFriend);
                    bc.sendTextMessage(toUsers, displayName + ", welcome to be my friend!", apiHttpClient);
                    Connection connection = null;
                    connection = DatabaseUrl.extract().getConnection();
                    toUsers = bc.getFriends(newFriend, connection);
                    if (toUsers.size() > 0) {
                        bc.sendTextMessage(toUsers, displayName + " just join us, let's welcome him/her!",
                                apiHttpClient);
                    }
                    bc.addFriend(newFriend, displayName, connection);
                    if (connection != null) {
                        connection.close();
                    }
                }
                break;
            default:
                // Unknown type?
            }
        }
        return "Events received successfully.";
    });

    get("/", (request, response) -> {
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("message", "Hello World!");
        return new ModelAndView(attributes, "index.ftl");
    }, new FreeMarkerEngine());
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = null;
    Statement stmt = null;//from w w  w . ja v a  2  s .  c  o  m

    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 = "INSERT INTO Person VALUES (1, 'A', 'B', 18)";
    stmt.executeUpdate(sql);
    sql = "INSERT INTO Person VALUES (2, 'C', 'D', 25)";
    stmt.executeUpdate(sql);
    sql = "INSERT INTO Person VALUES (3, 'E', 'F', 30)";
    stmt.executeUpdate(sql);
    sql = "INSERT INTO Person VALUES(4, 'S', 'M', 28)";
    stmt.executeUpdate(sql);
    stmt.close();
    conn.close();
}

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();/*from  w w w  .jav a 2 s  .c  om*/

    String query = "select * from survey where 1 = 0";

    WebRowSet webRS = new WebRowSetImpl();
    webRS.setCommand(query);
    webRS.execute(conn);

    // convert xml to a String object
    StringWriter sw = new StringWriter();
    webRS.writeXml(sw);
    System.out.println(sw.toString());

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