Java – how to fix com mysql. jdbc. exceptions. jdbc4. Mysqlnontransientconnectionexception: no operation is allowed after the connection is closed Exceptions?

This is a query for my records

public void saveTotal(JTextField txtGtotal,JTextField txtPTotal) {
    try {
        ResultSet rs = JDBC.getData("select MAX(or_id) as or_id from `order`");
        if (rs.first()) {
            if (rs.getInt("or_id") > 0) {
                try {
                    String date1 = new Validation().today();
                    boolean b1 = JDBC.putData("insert into transaction(tr_date,amount,tr_type) values ('" + date1 + "','" + txtGtotal.getText() + "','order')");
                    if (b1) {
                        try {
                            ResultSet rs1 = JDBC.getData("select MAX(tr_id) as tr_id from transaction");
                            if (rs1.first()) {
                                try {
                                    boolean b2 = JDBC.putData("insert into transaction(tr_date,'" + txtPTotal.getText() + "','profit')");
                                    if (b2) {
                                        try {
                                            ResultSet rs2 = JDBC.getData("select MAX(tr_id) as tr_id from transaction");
                                            if (rs2.first()) {

                                                try {
                                                    boolean b3 = JDBC.putData("insert into o_de(or_id,tr_id,oday,gtotal) values ('" + rs.getInt("or_id") + "','" + rs1.getInt("tr_id") + "','" + date1 + "','" + txtGtotal.getText() + "' )");
                                                    if (b3) {
                                                        try {
                                                            boolean b4 = JDBC.putData("insert into order_profit(or_id,ptotal) values ('" + rs.getInt("or_id") + "','" + txtPTotal.getText() + "' )");
                                                            if (b4) {
                                                                JDBC.commit();
                                                                JOptionPane.showMessageDialog(null,"Order Saved Sucessfully..");
                                                                JDBC.putClose();
                                                                JDBC.conClose();

                                                            }
                                                        } catch (Exception e) {
                                                            JDBC.rollback();
                                                            e.printStackTrace();
                                                        } finally {
                                                            JDBC.putClear();
                                                            JDBC.conClear();
                                                        }
                                                    }
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }

                                            }

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                } catch (Exception e) {
                                    JDBC.rollback();
                                    e.printStackTrace();
                                }
                            }
                        } catch (Exception e) {
                            JDBC.rollback();
                            e.printStackTrace();
                        }

                    }
                } catch (Exception e) {
                    JDBC.rollback();
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

This is my JDBC class

package Modle;

  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.sqlException;
  import java.sql.Statement;
  import java.util.logging.Level;
  import java.util.logging.Logger;

  public class JDBC {

static Connection con = null;
static boolean b;
static PreparedStatement state;

public static void setCon() {
    try {
        Class.forName("com.MysqL.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:MysqL://localhost:3306/lottery","root","123");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public static Connection getCon() throws Exception {
    if (con == null) {
        setCon();
    }
    return con;
}

public static boolean putData(String sql) {
    try {
        getCon().setAutoCommit(false);
        state = getCon().prepareStatement(sql);
        state.executeUpdate();
        b = true;
    } catch (Exception e) {
        e.printStackTrace();
        b = false;
    }
    return b;
}

// connection commit
public static void commit() {
    try {
        con.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

  // rollback data
  public static void rollback() {
    if (con != null) {
        try {
            con.rollback();
        } catch (sqlException ex) {
            Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,null,ex);
        }
    }
}

// close statement
public static void putClose() {
    try {
        state.close();
    } catch (sqlException ex) {
        Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
    }
}
 // close connection

  public static void conClose() {
    try {
        con.setAutoCommit(true);
        con.close();
    } catch (sqlException ex) {
        Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
    }
}

// clear prepared statement
public static void putClear() {
    try {
        if (state != null && !state.isClosed()) {
            state.close();
        }
    } catch (sqlException ex) {
        Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
    }
}

// clear the connection
public static void conClear() {
    try {
        if (con != null && !con.isClosed()) {
            con.setAutoCommit(true);
            con.close();
        }
    } catch (sqlException ex) {
        Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
    }
}

public static ResultSet getData(String sql) throws Exception {
    Statement state = getCon().createStatement();
    ResultSet rs = state.executeQuery(sql);
    return rs;
 }
 }

This is my first attempt at transaction processing in MySQL I know it's not an excuse But I have only a rough idea of this connection If my code is not perfect, please give me a demonstration answer

How to solve this problem? Allow operation after connection closing exception? thank you.

Added stack trace I think the same mistake was found in two other places They came before running the query

com.MysqL.jdbc.exceptions.jdbc4.MysqLNonTransientConnectionException: No operations allowed    after connection closed.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.MysqL.jdbc.Util.handleNewInstance(Util.java:411)
at com.MysqL.jdbc.Util.getInstance(Util.java:386)
at com.MysqL.jdbc.sqlError.createsqlException(sqlError.java:1013)
at com.MysqL.jdbc.sqlError.createsqlException(sqlError.java:987)
at com.MysqL.jdbc.sqlError.createsqlException(sqlError.java:982)
at com.MysqL.jdbc.sqlError.createsqlException(sqlError.java:927)
at com.MysqL.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1206)
at com.MysqL.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1198)
at com.MysqL.jdbc.ConnectionImpl.createStatement(ConnectionImpl.java:2484)
at com.MysqL.jdbc.ConnectionImpl.createStatement(ConnectionImpl.java:2466)
at Modle.JDBC.getData(JDBC.java:115)
at Controler.NewOrderCon2.saveTotal(NewOrderCon2.java:196)
at lottery.NewOrder.jButton6ActionPerformed(NewOrder.java:2350)
at lottery.NewOrder.access$1200(NewOrder.java:28)
at lottery.NewOrder$13.actionPerformed(NewOrder.java:537)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

Solution

Are you aware that you are actually accessing the back end in the GUI? You are passing parameters in text fields directly to the database This is the main source of fuckups At least verify your input, or little Bobby tables will terminate your work contract in advance

As for your error: sorry, but this code needs major refactoring This code does too much to count by line alone The first golden rule: keep your methods short The second golden rule: shorten them

In fact, you don't understand what's happening. It's a red light for you and shows that you need to reconsider your design

>Using JDBC Putdata() method for writing content independently. > For JDBC Getdata() performs the same operation. > See a pattern appear

I think it is the connection in JDBC Premature call to close() By dividing operations into more atomic operations, you can better reason code and understand the error at hand

Sorry, there is no solution, but in the long run, you'd better abide by some code principles Learn from them! The sooner the better, because I need more karma: read Robert C. Martin's "cleaning code" http://www.amazon.de/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882

Then you will embark on the path of enlightenment, so use daofactory (hint) and DAO design pattern (hint) and become a god of encoder congratulations!

Well, here's a little guide on how to look at refactoring Without completion and testing, I think I have completed the SQL insertion sequence (I don't know where to use transactionid) But I hope you can get an idea Have a nice day and welcome to Jamaica!

package MysqLfix;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.sqlException;
import java.sql.Statement;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextField;

public class JDBC {

    static Connection con = null;
    static boolean b;
    static PreparedStatement state;

    public static void setCon() {
        try {
            Class.forName("com.MysqL.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:MysqL://localhost:3306/lottery","123");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static Connection getCon() throws Exception {
        if (con == null) {
            setCon();
        }
        return con;
    }

    public static boolean putData(String sql) {
        try {
            getCon().setAutoCommit(false);
            state = getCon().prepareStatement(sql);
            state.executeUpdate();
            getCon().commit();
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
            b = false;
        }
        return b;
    }

// connection commit
    public static void commit() {
        try {
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // rollback data
    public static void rollback() {
        if (con != null) {
            try {
                con.rollback();
            } catch (sqlException ex) {
                Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
            }
        }
    }

// close statement
    public static void putClose() {
        try {
            state.close();
        } catch (sqlException ex) {
            Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
        }
    }
    // close connection

    public static void conClose() {
        try {
            con.setAutoCommit(true);
            con.close();
        } catch (sqlException ex) {
            Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
        }
    }

// clear prepared statement
    public static void putClear() {
        try {
            if (state != null && !state.isClosed()) {
                state.close();
            }
        } catch (sqlException ex) {
            Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
        }
    }

// clear the connection
    public static void conClear() {
        try {
            if (con != null && !con.isClosed()) {
                con.setAutoCommit(true);
                con.close();
            }
        } catch (sqlException ex) {
            Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
        }
    }

    public static ResultSet getData(String sql) throws Exception {
        Statement state = getCon().createStatement();
        ResultSet rs = state.executeQuery(sql);
        return rs;
    }

    public void saveTotal(JTextField txtGtotal,JTextField txtPTotal) {
        SuperDAO superDAO = new SuperDAO();

        if (superDAO.getMaxIdFromOrder() > 0) {
            Date date1;
            date1 = new Date();
            String txtGTotalFromTextField = txtGtotal.getText();
            String txtPTotalFromTextField = txtPTotal.getText();
            boolean b1 = false;
                    //regarding the transaction id...
            //this changes whilst updating the table transaction.

            int transactionId = -1;
            if (txtGTotalFromTextField.matches("[a-zA-Z]")) {
                transactionId = superDAO.insertOrderIntoTransaction(date1,txtGTotalFromTextField);
                //b1 = JDBC.putData("insert into transaction(tr_date,'" + txtGTotalFromTextField + "','order')");
            }
            if (transactionId > 0) {
                try {
                } catch (Exception ex) {
                    Logger.getLogger(JDBC.class.getName()).log(Level.SEVERE,ex);
                }
                if (txtPTotalFromTextField.matches("[a-zA-Z]")) {
                    transactionId = superDAO.insertProfitIntoTransaction(date1,txtGTotalFromTextField);
                }
                JDBC.putData("insert into o_de(or_id,gtotal) values ('" + superDAO.getMaxIdFromOrder() + "','" + transactionId + "','" + txtGtotal.getText() + "' )");
                JDBC.putData("insert into order_profit(or_id,ptotal) values ('" + superDAO.getMaxIdFromOrder() + "','" + txtPTotal.getText() + "' )");

                                                        //JDBC.commit();
                //JOptionPane.showMessageDialog(null,"Order Saved Sucessfully..");
                JDBC.putClose();
                JDBC.conClose();

            }

        }

    }

}



package MysqLfix;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.sqlException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author edm
 */
public class SuperDAO {

    Connection conn;

    public SuperDAO() {
        try {
            this.conn = JDBC.getCon();
        } catch (Exception ex) {
            Logger.getLogger(SuperDAO.class.getName()).log(Level.SEVERE,ex);
        }
    }

    public int getMaxIdFromOrder() {

        try {
            ResultSet rs = JDBC.getData("select MAX(or_id) as or_id from `order`");
            if (rs.first()) {

                return rs.getInt("or_id");
            }
        } catch (sqlException ex) {
            Logger.getLogger(SuperDAO.class.getName()).log(Level.SEVERE,ex);
        } catch (Exception ex) {
            Logger.getLogger(SuperDAO.class.getName()).log(Level.SEVERE,ex);
        }
        return -1;
    }

    public int getMaxIdFromTransaction() {
        ResultSet rs;
        try {
            rs = JDBC.getData("select MAX(tr_id) as tr_id from transaction");
            if (rs.first()) {
            return rs.getInt("tr_id");
        }
        } catch (Exception ex) {
            Logger.getLogger(SuperDAO.class.getName()).log(Level.SEVERE,ex);
        }
        return -1;
    }


    public int insertOrderIntoTransaction(Date date,String text) {
        JDBC.putData("insert into transaction(tr_date,tr_type) values ('" + date + "','" + text + "','order')");
        return getMaxIdFromTransaction();
    }

     public int insertProfitIntoTransaction(Date date,'profit')"); 

        return getMaxIdFromTransaction();
    }



}

Of course, the journey doesn't stop there I haven't finished JDBC savetotal() I've just started. You do the rest

Please note that I did not test this code against the database (some SQL DDL files are missing) In addition, I do not use rollback mechanism In addition, savetotal () exists in JDBC and does not belong to JDBC Use savetotal (if necessary) in the GUI to make all database access through superdao This is not the best design, but it is not too abstract. You can easily see how separation of concerns can make your code more readable and maintainable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>