程序在我点击“AddStudent”时卡住。

huangapple go评论75阅读模式
英文:

program freezes when I click AddStudent

问题

以下是你提供的代码的翻译部分:

数据库连接类(SmartData)

package smartdatabase;

import java.sql.*;

public class Conn {

    private Connection connect = null;
    private Statement stmt = null;
    private PreparedStatement ps = null;

    public Conn() {
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            connect = DriverManager.getConnection("jdbc:derby://localhost:1527/SmartData;create=true", "root", "password");
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ResultSet getStudents() {
        try {
            String sql;
            sql = "SELECT FirstName, Surname FROM tblStudents";
            stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            stmt.executeQuery(sql);
            ResultSet rs = stmt.getResultSet();
            if (!rs.first()) {
                System.out.println("Empty ResultSet");
            } else {
                do {
                    String Firstname = rs.getString("Firstname");
                    String Surname = rs.getString("surname");
                    System.out.println(Firstname + "    " + Surname);
                } while (rs.next());
            }
            return rs;
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }

    public void addStudent(String fn, String sn, int kid) {
        try {
            String qry = "INSERT INTO TblStudents(FirstName, Surname, Kid) VALUES(?,?,?)";
            ps = connect.prepareStatement(qry);
            ps.setString(1, fn);
            ps.setString(2, sn);
            ps.setInt(3, kid);
            ps.executeUpdate();
            ps.close();
            connect.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }

    String getKidsNamebyKid(int i) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    String getCentreNamebyCid(int i) {
         String out = "Error, centre not found";
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            connect = DriverManager.getConnection("jdbc:derby://localhost:1527/SmartData;create=true", "root", "password");
            String qry = "SELECT CENTRENAME FROM TBLCENTRES WHERE CID = ?";
            ps = connect.prepareStatement(qry);
            ps.setInt(1, i);
            ps.executeQuery();
            out = ps.getResultSet().toString();
            ps.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }

            try {
                if (connect != null) {
                    connect.close();
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        return out;
    }
}

添加新学生类

package smartdatabase;

public class AddStudent extends javax.swing.JFrame {
    private Conn con = new Conn();

    public AddStudent() {
        initComponents();
        int i = 0;
        while (con.getCentreNamebyCid(i) != null) {
            jcbCentre.addItem(con.getCentreNamebyCid(i));
            i++;
        }
    }

    private void initComponents() {
        // ...(这部分是界面布局等代码,已略去)
    }

    private void jfcPDFActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                      

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
        con.addStudent(txbFirstName.getText(), txbSurname.getText(), 1);
    }                                      

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AddStudent().setVisible(true);
            }
        });
    }
}

请注意,上面翻译的内容仅为代码部分的翻译,与原始代码相对应。如果你遇到了程序冻结的问题,原因可能不仅仅在于翻译的代码部分,还可能与其他因素有关,比如GUI的事件处理、数据库连接等。程序冻结需要详细的调试和问题定位才能找到解决办法。如果需要进一步的帮助,请提供更多上下文和错误信息。

英文:

Connection class to database (SmartData)

package smartdatabase;
/**
*
* @author travi
*/
import java.sql.*;//Import neccessary libraries for program
public class Conn {
private Connection connect = null;//declare connection
private Statement stmt = null;//declare statement
private PreparedStatement ps = null;//declare preparedstatement
public Conn() {//default constructor
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/SmartData;create=true", "root", "password");//establish connection
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public ResultSet getStudents() {
try {//try for errors
//establishing connection
String sql;//declare string for SQL command
sql = "SELECT FirstName, Surname FROM tblStudents";//setting SQL command
stmt = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);//creating statement
stmt.executeQuery(sql);//execute statement
ResultSet rs = stmt.getResultSet();//collect query results
if (!rs.first()) {//checking if results are empty
System.out.println("Empty ResultSet");//error for empty resultset
} else {
do {
String Firstname = rs.getString("Firstname");
String Surname = rs.getString("surname");
System.out.println(Firstname + "    " + Surname);//this was not for final output, only for testing purposes, which I never got past
} while (rs.next());//while rs is not empty
}
return rs;//returning resultset
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void addStudent(String fn, String sn, int kid) {//method to add new student to database
try {//trying for errors
String qry = "INSERT INTO TblStudents(FirstName, Surname, Kid) VALUES(?,?,?)";//setting query command
ps = connect.prepareStatement(qry);//preparing statement
ps.setString(1, fn);//setting FirstName 
ps.setString(2, sn);//setting Surname
ps.setInt(3, kid);//setting ID of classroom student is in
ps.executeUpdate();//running command
//cache cleanup
ps.close();
connect.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {//cache cleanup
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
String getKidsNamebyKid(int i) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
String getCentreNamebyCid(int i) {
String out = "Error, centre not found";
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/SmartData;create=true", "root", "password");
String qry = "SELECT CENTRENAME FROM TBLCENTRES WHERE CID = ?";//setting query command
ps = connect.prepareStatement(qry);//preparing statement
ps.setInt(1, i);//setting CID
ps.executeQuery();//running command
out = ps.getResultSet().toString();
ps.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {//cache cleanup
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (connect != null) {
connect.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
return out;
}
}

Add new student class

package smartdatabase;
/**
*
* @author travi
*/
public class AddStudent extends javax.swing.JFrame {
private        Conn con = new Conn();
/**
* Creates new form AddStudent
*/
public AddStudent() {
initComponents();
int i=0;
while(con.getCentreNamebyCid(i)!=null){
jcbCentre.addItem(con.getCentreNamebyCid(i));
i++;
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {
lblTitle = new javax.swing.JLabel();
lblFirstName = new javax.swing.JLabel();
lblSurname = new javax.swing.JLabel();
lblCentre = new javax.swing.JLabel();
lblKids = new javax.swing.JLabel();
txbFirstName = new javax.swing.JTextField();
txbSurname = new javax.swing.JTextField();
jfcPDF = new javax.swing.JFileChooser();
jcbCentre = new javax.swing.JComboBox<>();
jcbKids = new javax.swing.JComboBox<>();
btnCancel = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
btnAdd = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblTitle.setText("Add new student");
lblFirstName.setText("First Name:");
lblSurname.setText("Surname:");
lblCentre.setText("Centre:");
lblKids.setText("Class:");
jfcPDF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jfcPDFActionPerformed(evt);
}
});
btnCancel.setText("Cancel");
jLabel6.setText("Please select the PDF containing the student's documents");
btnAdd.setText("Add Student");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(109, 109, 109)
.addComponent(jfcPDF, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnAdd))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnCancel))
.addGroup(layout.createSequentialGroup()
.addGap(191, 191, 191)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblFirstName)
.addComponent(lblSurname, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblCentre, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(lblKids, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txbFirstName, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txbSurname, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jcbCentre, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jcbKids, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(jLabel6))))
.addContainerGap(12, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblTitle)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblFirstName)
.addComponent(txbFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblSurname)
.addComponent(txbSurname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCentre)
.addComponent(jcbCentre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblKids)
.addComponent(jcbKids, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jfcPDF, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAdd))
.addGap(0, 0, 0)
.addComponent(btnCancel)
.addContainerGap())
);
pack();
}// </editor-fold>                        
private void jfcPDFActionPerformed(java.awt.event.ActionEvent evt) {                                       
// TODO add your handling code here:
}                                      
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
con.addStudent(txbFirstName.getText(),txbSurname.getText(),1);
}                                      
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddStudent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddStudent().setVisible(true);
}
});
}
// Variables declaration - do not modify                     
private javax.swing.JButton btnAdd;
private javax.swing.JButton btnCancel;
private javax.swing.JLabel jLabel6;
private javax.swing.JComboBox<String> jcbCentre;
private javax.swing.JComboBox<String> jcbKids;
private javax.swing.JFileChooser jfcPDF;
private javax.swing.JLabel lblCentre;
private javax.swing.JLabel lblFirstName;
private javax.swing.JLabel lblKids;
private javax.swing.JLabel lblSurname;
private javax.swing.JLabel lblTitle;
private javax.swing.JTextField txbFirstName;
private javax.swing.JTextField txbSurname;
// End of variables declaration                   
}

Wish I could give more information, but there isn't even an error code, it just freezes and I can't close or interact with the program anymore, any help is appreciated. The addstudent is called via a button on the main menu (constructs a addStudent object, sets visibile to true) and the moment I click the button it just stops.

答案1

得分: 1

你的 getCentreNamebyCid 永远不会返回 null,因此 while(con.getCentreNamebyCid(i)!=null) 总是为真。所以,我认为在 getCentreNamebyCid 中不应该初始化 String out

String getCentreNamebyCid(int i) {
String out;
try {
...
英文:

Your getCentreNamebyCid never return null, so while(con.getCentreNamebyCid(i)!=null) is always true. So, I think, You should not initialize String out in getCentreNamebyCid

String getCentreNamebyCid(int i) {
String out;
try {
...

huangapple
  • 本文由 发表于 2020年9月2日 22:05:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63707293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定