这可能是一个愚蠢的问题,因为我是一个初学者,但无论如何:我有一个程序使用名为 connectToDatabase() 的方法连接到嵌入式数据库。我在 JFrameForm 中使用它,每次调用它都会被调用两次。这是代码:
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);
}
});
}
从另一个名为 StartUp 的类:
SetupAccounts sa = new SetupAccounts();
sa.runsetupaccounts();