搜索
首页JavaSQL 连接关闭而不提示

php小编鱼仔为您带来最新的Java问答:SQL连接关闭而不提示。在开发过程中经常会遇到SQL连接未关闭而不提示的问题,这可能会导致资源泄露和性能问题。本文将为您详细解答这一问题,并提供解决方案,帮助您更好地处理SQL连接关闭的相关情况。让我们一起来了解吧!

问题内容

当尝试依次运行两个 sql 查询时(如 dbtest2 中所示),系统会返回一条错误,指出 sql 连接已关闭,即使尚未提示这样做。

到目前为止,我已尝试将 sqlconn 连接移动到不同的位置,以及按方法单独打开和关闭连接。如果只调用一个 sql 查询,系统就会按预期工作。这些是类:

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();
            }
        }
    }
}
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;     
    }
}
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"));
        }
    }
}

尽管付出了一切努力,我最终收到的错误消息是:

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

期望的结果是输出只是列表

解决方法

那是因为您正在使用尝试资源。请参阅 https://www.php.cn/link/533a7de111ee3af214eee5e09e3fa1bc 了解更多详情。

这意味着当您将连接放入 try 块中时。 try 块执行后连接关闭:

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

只需尝试将连接移到 try 块之外,如下所示:

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

执行完所有查询后,不要忘记关闭连接。

请注意,另一个选项是每次打开一个新连接。

以上是SQL 连接关闭而不提示的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
4 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
1 个月前By尊渡假赌尊渡假赌尊渡假赌

热工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。