Table of Contents
Question content
Workaround
Home Java SQL connection closed without prompt

SQL connection closed without prompt

Feb 22, 2024 pm 12:46 PM

php editor Yuzai brings you the latest Java Q&A: SQL connection is closed without prompting. During the development process, we often encounter the problem that the SQL connection is not closed without prompting, which may lead to resource leaks and performance problems. This article will answer this question in detail and provide solutions to help you better handle situations related to SQL connection closing. Let’s find out together!

Question content

When trying to run two sql queries one after the other (as shown in dbtest2), the system returns an error stating that the sql connection has been closed, even though it has not been prompted to do so.

So far I have tried moving the sqlconn connection to a different location, as well as opening and closing the connection individually by method. If I just call a sql query, the system works as expected. These are the classes:

import java.sql.*;

public class mysqlconnect {
    private static final string db_url = "jdbc:mysql://dbconnectionurl";
    private static final string user = "username";
    private static final string password = "pass";
    private static connection mysqlconn;

    static {
        try {
            class.forname("com.mysql.cj.jdbc.driver");
            mysqlconn = drivermanager.getconnection(db_url, user, password);
            system.out.println("mysql db connection is successful");
        } catch (classnotfoundexception | sqlexception e) {
            e.printstacktrace(); // handle classnotfoundexception and sqlexception
        }
    }

    public static connection getmysqlconnection() {
        return mysqlconn;
    }

    public static void closeconnection() {
        if (mysqlconn != null) {
            try {
                mysqlconn.close();
                system.out.println("mysql db connection is closed");
            } catch (sqlexception e) {
                e.printstacktrace();
            }
        }
    }
}
Copy after login
import java.sql.*;
import java.util.arraylist;

public class sqlquery {
    private int userid;
    private string password;
    private boolean activated;
    private string usertype;
    
    connection sqlconn = mysqlconnect.getmysqlconnection(); // i want to be able to try accept this but idk how

    public string sqlsearch(string tbname){ // all
        string sqlquery = "";

        if(tbname == ""){
            throw new illegalargumentexception("criteria cannot be empty");
        }

        sqlquery = "select * from " + tbname + ";";
        
        if(sqlquery == ""){
            throw new illegalargumentexception("sql query not set, something gone wrong");
        }

        arraylist<string> resultlist = new arraylist<string>();

        try (connection connection = sqlconn;
            preparedstatement ps = connection.preparestatement(sqlquery);
            resultset rs = ps.executequery()) {
    
            resultsetmetadata metadata = rs.getmetadata();
            int columncount = metadata.getcolumncount();
        
            if (rs.next()) {
                for (int i = 1; i <= columncount; i++) {
                    string columnvalue = rs.getstring(i);
                    resultlist.add(columnvalue);
                }     
            } else {
                system.out.println("no match for " + tbname);
            }
        
        } catch (sqlexception e) {
            system.err.println("error executing sql query: " + e.getmessage());
            e.printstacktrace(); 
        }
        string result = string.join(", ", resultlist);
        return result;     
    }
}
Copy after login
public class dbtest2 {
    public class main {
        public static void main(string[] args) {    
            person person = new person(2, "password123", true, "student");

            system.out.println(person.sqlsearch("course"));
            system.out.println(person.sqlsearch("student"));
        }
    }
}
Copy after login

Despite all my efforts, the error message I finally received was:

MySQL Db Connection is successful
CS101, CSC 101, Intro to Computer Science, 3
Error executing SQL query: No operations allowed after connection closed.
java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:111)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:98)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:90)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:64)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:74)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:73)
        at com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1610)
        at com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1524)
        at Person.sqlSearch(Person.java:245)
        at dBtest2$Main.main(dBtest2.java:8)
Caused by: com.mysql.cj.exceptions.ConnectionIsClosedException: No operations allowed after connection closed.
        at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:62)
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:502)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:486)
        at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
        at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:104)
        at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:149)
        at com.mysql.cj.NativeSession.checkClosed(NativeSession.java:756)
        at com.mysql.cj.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:556)
        at com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1539)
        ... 3 more
Copy after login

The desired result is that the output is just a list

Workaround

That's because you are using try resources. Please see https://www.php.cn/link/533a7de111ee3af214eee5e09e3fa1bc for more details.

This means when you put the connection in a try block. The connection is closed after the try block is executed:

try (connection connection = sqlconn;
     preparedstatement ps = connection.preparestatement(sqlquery);
     resultset rs = ps.executequery()) {
Copy after login

Just try moving the connection outside the try block like this:

Connection connection = sqlConn;
try (PreparedStatement ps = connection.prepareStatement(sqlQuery);
     ResultSet rs = ps.executeQuery()) {
Copy after login

After executing all queries, don’t forget to close the connection.

Please note that another option is to open a new connection each time.

The above is the detailed content of SQL connection closed without prompt. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)