Common Errors During Java Database Operations

Source: Internet
Author: User

Database Connection is an object that we usually create connection, statement, and resultset. New users may use the following:

Connection connection = drivermanager. getconnection ("Database URL"); Statement statement = connection. createstatement (); // The JDBC code resultset = ............ Resultset. Close (); statement. Close (); connection. Close ();

The above method is incorrect. Because if you create a connection with a databaseGetconnection () andWhen an exception (sqlexception) is thrown between close (), close () is ignored completely.

The correct way to release database connections and JDBC resources is to put close () in the Finally block for try-catch-finally exception handling. Modify as follows:

Connection connection = NULL; Statement statement = NULL; resultset = NULL; try {connection = drivermanager. getconnection ("Database URL"); Statement = connection. createstatement (); // The JDBC code resultset = ...... ......} Catch (sqlexception e ){......} Finally {If (resultset! = NULL) {resultset. Close ();} If (statement! = NULL) {statement. Close ();} If (statement! = NULL) {connection. Close ();}}

However, close may also throw a sqlexception exception. When the program runs to resultset. Close (), it throws a sqlexception exception, and the next statement is ignored. Therefore, the safest way is to use try-catch for each close (), as shown below:

Connection connection = NULL; Statement statement = NULL; resultset = NULL; try {connection = drivermanager. getconnection ("Database URL"); Statement = connection. createstatement (); // follow the JDBC code resultset = ............ Resultset = ...... } Catch (sqlexceptione ){...... } Finally {try {resultset. close ();} catch (sqlexceptione) {} Try {statement. close ();} catch (sqlexceptione) {} Try {connection. close () ;}catch (sqlexceptione ){}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.