hamchi
hamchi

Reputation: 161

Using a database connection from a different jframe

i got this declared in one jframe (Main)

 Connection con;

i want to use that same connection in a other jframe(Gegevens)

 try {
        PreparedStatement stat1 = con.prepareStatement("SELECT idrecepten , p.naam , p.achternaam , m.naam , m.fabrikant , m.dosering FROM recepten r JOIN patienten p ON r.patient = p.idpatienten JOIN medicijnen m ON r.medicijn = m.idmedicijnen WHERE r.patient = ? ");
        stat1.setString(1,primarykey[0]);
        ResultSet resultaat = stat1.executeQuery();

        while(resultaat.next())
        {
           gegevens.model2.addElement(resultaat.getString(1)+" "+ resultaat.getString(2) +" "+ resultaat.getString(3)+" "+ resultaat.getString(4) +" "+ resultaat.getString(5) +" " + resultaat.getString(6));
        }

    } catch (SQLException ex) {
        System.out.println(ex);
    } 

as you can see i am filling the model2 from the jframe(Main), but i want to fill the model in the constructor of the OTHER jframe(Gegevens), same result different approach. BUT

i want to use one only database connection so do i or do i not use the same database connect if i do this:

 Main main = new Main();

and then use the connection

 main.con

Upvotes: 1

Views: 674

Answers (1)

Kevin Mangold
Kevin Mangold

Reputation: 1155

The best approach is to construct your code so that when the second/other JFrames are instantiated, that you pass the Connection object as a parameter to the constructor.

Upvotes: 1

Related Questions