private void connectToDatabase()被称为两次?

时间:2012-07-10 18:44:08

标签: database embedded

这可能是一个愚蠢的问题,因为我是初学者但无论如何:我有一个程序使用一个名为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();
}

这真令人困惑,有人可以帮忙吗?

我知道它会被调用两次,因为我收到两条错误消息,内容相同'架构'app''中已存在'USERACCOUNTS表'。

从这里调用构造函数:

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();

1 个答案:

答案 0 :(得分:1)

你帖子的最后两行讲述了这个故事。首先,构造一个SetupAccounts的实例,构造函数调用connectToDatabase()。然后,您在该实例上调用runsetupaccounts()runsetupaccounts()构建SetupAccounts第二个实例,其构造函数调用{{ 1}}。

也许您应该将connectToDatabase()设为静态方法,这样您就可以先调用它而不先创建runsetupaccounts()对象。