【问题标题】:JComboBox returns Null Pointer ExceptionJComboBox 返回空指针异常
【发布时间】:2018-09-04 15:01:05
【问题描述】:

我正在做一个 Java 包交付项目。

我正在尝试使用数据库中的数据加载两个 JComboBox 组件,但出现以下错误。

麻袋追踪

    Names : java.sql.SQLNonTransientConnectionException: 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:108)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:87)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:61)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:71)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:73)
    at com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1829)
    at com.mysql.cj.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:1732)
    at Modelo.UsuarioDAO.usuarios_combo(UsuarioDAO.java:178)
    at Presentacion.ListarEncomiendasAdmin$1.run(ListarEncomiendasAdmin.java:62)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$400(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

这是我在名为UsuarioDAO 的类中填充组合框的代码。

    public JComboBox usuarios_combo(){
         JComboBox cbox_usuarios = new JComboBox();
         try {

             String sql = "SELECT usu_ci FROM usuarios";
             Connection conn = this.getConexion(); // in here i have a message which prints ok if connection succeeded so i guess the problem won't be here
             PreparedStatement pst1 = conn.prepareStatement(sql);
             pst1.setQueryTimeout(5);
             ResultSet rs = pst1.executeQuery();

             while ((rs != null) && (rs.next())) {

                 String ci = rs.getString("usu_ci");
                 cbox_usuarios.addItem(ci);
             }

             pst1.close();
             rs.close();
             conn.close();

         }
         catch (Exception e) {
             System.err.println("Names : " + e.getClass().getName() + ": " + e.getMessage());
             e.printStackTrace();
         }        
         return cbox_usuarios;
     }

然后,在我要加载两个组合框的框架中,我有以下代码:

public class ListarEncomiendasAdmin extends JFrame {

    private JPanel contentPane;
    private JTextField txtEstado;
    private JTextField txtOrigen;
    private JTextField txtDestino;
    private static JTable tblEncomiendas;
    private static EncomiendasDAO eDAO = new EncomiendasDAO();
    private static Object[][] dtEncomienda;
    private static JComboBox cmbRemitente;
    private static JComboBox cmbDestinatario;
    
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            UsuarioDAO uDAO = new UsuarioDAO(); 
            try {
                cmbRemitente = new JComboBox();
                cmbDestinatario = new JComboBox();
                ListarEncomiendasAdmin frame = new ListarEncomiendasAdmin();
                frame.setVisible(true);
                Actualizar_Tabla();
                cmbRemitente = uDAO.usuarios_combo();
                cmbDestinatario = uDAO.usuarios_combo();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

连接代码

public class ConexionBD {
    
    /* Datos para la conexion */
    private String bd = "proy_encomiendas";//Base de datos
    private String user = "root"; //Usuario
    private String password = ""; //Contraseña
    private String host = "jdbc:mysql://localhost/"+bd; //Servidor + Base de datos
    public static Connection conn = null; //Inicializamos con valor null la conexion
    
    /* Constructor de la clase que se conecta a la Base de Datos */
    public ConexionBD(){
        try{
            //Driver para MySQL
            Class.forName("com.mysql.jdbc.Driver");
            
            //Obtenemos la conexión
            conn = DriverManager.getConnection(host,user,password);
            if (conn!=null){
                System.out.println("Se conecto a la base de datos "+bd+"");
            }
        }catch(SQLException e){
            System.out.println("Error en la ejecución:" + e.getErrorCode() + " " + e.getMessage());
        }catch(ClassNotFoundException e){
            System.out.println(e);
        }
    }

    public Connection getConexion(){
        return ConexionBD.conn;
    }

我调试了应用程序,结果证明它正在从数据库中获取数据(我可以看到它应该加载到组合框中的具有不同数字的迭代),但最终当框架显示时,两者组合框是空的,我得到一个 SQLNonTransient 异常。

所以,如果您能提供任何帮助,我们将不胜感激。提前致谢。

编辑:连接是通过 JDBC 我正在使用包含 MYSQL 的 wampserver。

【问题讨论】:

  • 正如您在堆栈跟踪中看到的,在执行语句之前连接已关闭。你能添加你的连接代码吗?
  • 也许这会对你有所帮助:stackoverflow.com/questions/6172930/…
  • @ItFreak 在那里添加了连接代码。
  • 似乎 ConexionBD 类没有实例化(使用 new 关键字创建)。你调用 this.getCeonnexion,所以我认为从来没有创建到数据库的连接

标签: java mysql swing jcombobox


【解决方案1】:

更改您的 ConexionBD 类代码,如下所示在静态块中加载驱动程序,每次调用 getConexion 方法时创建新的数据库连接。

static {
    try{
        //Driver para MySQL
        Class.forName("com.mysql.jdbc.Driver");
    } catch(ClassNotFoundException e){
        System.out.println(e);
    }
 }

 public ConexionBD() {
 }

  public Connection getConexion(){
    Connection conn = null;
    try {
         conn = DriverManager.getConnection(host,user,password);
         if (conn!=null){
            System.out.println("Se conecto a la base de datos "+bd+"");
         }
    } catch(SQLException e){
        System.out.println("Error en la ejecución:" + e.getErrorCode() + " " + e.getMessage());
    }
    return conn; 
  }

【讨论】:

    猜你喜欢
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    相关资源
    最近更新 更多