1
這可能是一個愚蠢的問題,因爲我是一個初學者,但無論如何:我有一個程序,使用名爲connectToDatabase()的方法連接到嵌入式數據庫。我在JFrameForm中使用它,每次我調用它時,它會被調用兩次。下面是代碼:private void connectToDatabase()被稱爲兩次?
private void connectToDatabase() {
String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
String CONNECTION = "jdbc:derby:db";
try {
Class.forName(DRIVER).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Fatal Error: " + ex.getMessage(), "Fatal Error!", JOptionPane.ERROR_MESSAGE);
}
try {
connection = DriverManager.getConnection(CONNECTION);
statement = connection.createStatement();
statement.executeUpdate("create table USERACCOUNTS (ID INTEGER NOT NULL PRIMARY KEY, USERNAME VARCHAR(32), PASSWORD VARCHAR(32))");
resultset = statement.executeQuery("SELECT * FROM USERACCOUNTS");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Fatal Error: " + ex.getMessage(), "Fatal Error!", JOptionPane.ERROR_MESSAGE);
}
}
在這裏,在構造函數中調用它:
public SetupAccounts() {
initComponents();
this.setLocationRelativeTo(null);
connectToDatabase();
}
這實在是混亂,任何人都可以幫助嗎?
我知道它被調用了兩次,因爲我得到了兩個具有相同內容的錯誤消息'USERACCOUNTS表已經存在於模式'app'中。
的構造函數將被從這裏叫:
public void runsetupaccounts() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException err) {
JOptionPane.showMessageDialog(null, "Look and feel not set: " + err.getMessage());
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SetupAccounts().setVisible(true);
}
});
}
從另一個類調用安裝調試:
SetupAccounts sa = new SetupAccounts();
sa.runsetupaccounts();
非常感謝,它的工作! – armin302 2012-07-11 08:16:22