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