数据库操作后关闭语句? [英] Closing statement after database operation?

查看:140
本文介绍了数据库操作后关闭语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

声明声明; 连接连接;

Statement statement; Connection connection;

每次执行以下数据库操作后,我将关闭连接.

I am closing connection after every database operation as below.

connection.close();

我创建了如下的语句对象.

i created statement object as below.

connection.createStatement(....)

我是否也需要关闭连接类似于连接关闭?

Do i need to close satement also similar to connection closing?

我的意思是我需要打电话给statement.close();吗?

如果不调用会发生什么?

What will happen if it is not called?

谢谢!

推荐答案

Statement.close()

立即释放此Statement对象的数据库和JDBC资源,而不是等待它自动关闭时发生. 通常最好在使用完资源后立即释放资源,以避免占用数据库资源.

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources.

一种确保始终调用close()的好方法是将其放置在finally块中:

One good way to ensure that close() is always called is by placing it inside a finally block:

Statement stmt = connection.createStatement();
try {
    // use `stmt'
} finally {
    stmt.close();
}

在Java 7中,以上内容可以更简洁地写为:

In Java 7, the above can be more concisely written as:

try (Statement stmt = connection.createStatement()) {
    // ...
}

这称为 try -with-resources语句.

This is called the try-with-resources statement.

这篇关于数据库操作后关闭语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆