How to close a JDBC database connection?

After connecting to the database using JDBC, it is necessary to manually close the database connection. This can be done by calling the `close()` method to close the database connection. The specific steps are as follows: 1. Create a `Connection` object to establish a connection with the database. 2. After completing database operations, call the `close()` method of the `Connection` object to close the database connection. Here is an example code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class CloseConnectionExample {

    public static void main(String[] args) {

        Connection conn = null;

        try {

            // 创建数据库连接

            conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/mydatabase”,              “username”, “password”);

            // 执行数据库操作

        } catch (SQLException e) {

            e.printStackTrace();

        } finally {

            if (conn != null) {

                try {

                    // 关闭数据库连接

                    conn.close();

                } catch (SQLException e) {

                    e.printStackTrace();

                }

            }

        }

    } }

In the example above, the method conn.close() is called in the finally block to ensure that the database connection is properly closed regardless of whether an exception occurs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds