1

It is probably a stupid question because I am a beginner but anyways: I have a program that connects to an embedded database using a method called connectToDatabase(). I am using it inside a JFrameForm and everytime i call it it gets called twice. Here is the code:

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

}

And here the call for it in the constructor:

public SetupAccounts() {
    initComponents();
    this.setLocationRelativeTo(null);
    connectToDatabase();
}

It is really confusing, can anyone help please?

I know it gets called twice because I get two error messages with the same content 'USERACCOUNTS table exists already in schema 'app''.

The constructor gets called from here:

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

From another class called StartUp:

SetupAccounts sa = new SetupAccounts();
sa.runsetupaccounts();
4

1 に答える 1

1

投稿の最後の 2 行が物語っています。まず、 のインスタンスを構築しSetupAccounts、コンストラクターが を呼び出しますconnectToDatabase()。次にrunsetupaccounts()、そのインスタンスを呼び出し、 の2 番目のインスタンスをrunsetupaccounts()構築し、そのコンストラクターを呼び出します。SetupAccountsconnectToDatabase()

おそらく、最初にオブジェクトrunsetupaccounts()を作成せずに呼び出すことができるように、静的メソッドを作成する必要があります。SetupAccounts

于 2012-07-10T19:31:52.833 に答える