# 断开与 TiDB 服务器实例的连接
+ 使用 `Connection.close()` 
```
...
finally{
            if(connection != null){
                try{
                    // Release the resources in cascade
                    ~!@connection.close()@!~;
                    System.out.println("Connection closed");
                }
                catch(Exception e){
                    System.out.println("Error disconnecting: "+e.toString());
                }
            }
        }
```
------------------------------------------------------------------------

演示脚本:

对于 macOS 和 Linux:https://github.com/pingcap/tidb-course-201-lab/blob/master/scripts/09-demo-jdbc-connection-01-show.sh

对于 Windows:https://github.com/pingcap/tidb-course-201-lab/blob/master/scripts/09-demo-jdbc-connection-01-show.bat


当你的程序使用完了 TiDB 服务器后,终止连接。最佳做法是,要立即释放资源,必须显式关闭连接。

要断开与 TiDB 服务器的连接,请使用连接对象的 close () 方法。

本幻灯片中示例中的代码从上一张幻灯片中的代码继续。它尝试在 finally {} 区块中断开与 TiDB 服务器的连接。无论上一张幻灯片中用于连接数据库的代码是否成功,finally {} 块中的代码都会执行。close () 方法依赖于连接对象,因此,首先我们要确保存在有效的 Connection 对象,如果连接不等于 null。

如果没有连接实例,则程序结束。如果存在连接实例,则它会尝试调用连接对象的 close () 方法。如果成功,程序将报告连接已关闭。如果由于任何原因无法关闭连接,则程序会执行 catch {} 块中的代码,该代码块会在退出前向用户报告错误。

```
...
finally{
            if(connection != null){
                try{
                    // Release the resources in cascade
                    connection.close();
                    System.out.println("Connection closed");
                }
                catch(Exception e){
                    System.out.println("Error disconnecting: "+e.toString());
                }
            }
        }
```
