2017-07-17 7 views
0

Ich benutze MySQL 5.7, ich habe ein paar Datenbanken erstellt. Ich habe sie angezeigt ein Drop down [JComboBox] in NetBeans IDE 8.2Wie bekomme ich eine dynamische Verbindung zur MySQL-Datenbank in Java und zeige Tabellen, Attribute aus der ausgewählten Datenbank?

Datenbank

+-------------------- 
| classicmodels 
| db1 
| db2 

Nach erforderlich ist

Wenn DB1 (jeder angezeigte Wert ausgewählt werden kann) ausgewählt ist, ich will um eine Verbindung zu ihm zu bekommen. Zeigen Sie dann Tabellen in einem Fenster und die Attribute/Spalten unter jeder Tabelle in einem Fenster an.

Database.java

import java.sql.*; 
import java.util.ArrayList; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.JOptionPane; 

public class Database extends javax.swing.JFrame { 
    Connection conn = null; 
    Statement stmt = null; 
    ResultSet rs = null; 

    /** 
    * Creates new form Database 
    */ 
    public Database() { 
     initComponents(); 
     java.util.ArrayList<String> tables = new ArrayList<>(); 
     conn = MySqlConnect.ConnectDB(); 
     String sql = "show databases;"; 
     try { 
      stmt = conn.createStatement(); 
      stmt.execute(sql); 
      rs = stmt.getResultSet(); 
      while (rs.next()) { 
       jComboBox1.addItem(rs.getString("Database")); 
      } 

     } catch (SQLException ex) { 
      Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     if (null != selection) { 
      selection.setVisible(false); 
     } 

    } 

    /** 
    * This method is called from within the constructor to initialize the form. 
    * WARNING: Do NOT modify this code. The content of this method is always 
    * regenerated by the Form Editor. 
    */ 
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    private void initComponents() { 

     jMenuItem1 = new javax.swing.JMenuItem(); 
     jMenuItem2 = new javax.swing.JMenuItem(); 
     jMenuItem3 = new javax.swing.JMenuItem(); 
     jComboBox1 = new javax.swing.JComboBox<>(); 

     jMenuItem1.setText("jMenuItem1"); 

     jMenuItem2.setText("jMenuItem2"); 

     jMenuItem3.setText("jMenuItem3"); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 
     setTitle("Available DataSources"); 
     setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N 
     setForeground(new java.awt.Color(51, 0, 255)); 

     jComboBox1.addItemListener(new java.awt.event.ItemListener() { 
      public void itemStateChanged(java.awt.event.ItemEvent evt) { 
       jComboBox1ItemStateChanged(evt); 
      } 
     }); 
     jComboBox1.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jComboBox1ActionPerformed(evt); 
      } 
     }); 
     jComboBox1.addKeyListener(new java.awt.event.KeyAdapter() { 
      public void keyPressed(java.awt.event.KeyEvent evt) { 
       jComboBox1KeyPressed(evt); 
      } 
     }); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(layout.createSequentialGroup().addGap(159, 159, 159) 
         .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 
           javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
         .addContainerGap(213, Short.MAX_VALUE))); 
     layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(layout.createSequentialGroup().addGap(92, 92, 92) 
         .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 
           javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
         .addContainerGap(401, Short.MAX_VALUE))); 

     setBounds(0, 0, 416, 552); 
    }// </editor-fold> 

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) { 
     // TODO add your handling code here: 
     selection = new QueryPredictor(jComboBox1.getSelectedItem().toString()); 
     selection.setVisible(true); 

    } 

    private void jComboBox1KeyPressed(java.awt.event.KeyEvent evt) { 
     // TODO add your handling code here: 
    } 

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) { 
     // TODO add your handling code here: 
    } 

    /** 
    * @param args 
    *   the command line arguments 
    */ 
    public static void main(String args[]) { 

     try { 
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(info.getName())) { 
        javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(Database.class.getName()).log(java.util.logging.Level.SEVERE, 
        null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(Database.class.getName()).log(java.util.logging.Level.SEVERE, 
        null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(Database.class.getName()).log(java.util.logging.Level.SEVERE, 
        null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(Database.class.getName()).log(java.util.logging.Level.SEVERE, 
        null, ex); 
     } 
     // </editor-fold> 

     /* Create and display the form */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new Database().setVisible(true); 
      } 
     }); 
    } 

    // Variables declaration - do not modify 
    private javax.swing.JComboBox<String> jComboBox1; 
    private javax.swing.JMenuItem jMenuItem1; 
    private javax.swing.JMenuItem jMenuItem2; 
    private javax.swing.JMenuItem jMenuItem3; 
    // End of variables declaration 
} 

MySqlConnect.java

import java.sql.*; 
import javax.swing.JOptionPane; 

public class MySqlConnect { 
    Connection conn = null; 

    public static Connection ConnectDB() { 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
      Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels", "root", "system"); 
                  //"jdbc:mysql://localhost:3306/db1","root","system"); 
                  //"jdbc:mysql://localhost:3306/db2","root","system");   

      return conn; 

     } catch (Exception e) { 
      JOptionPane.showMessageDialog(null, e); 
      return null; 
     } 
    } 

} 

Antwort

0

passieren einen Parameter für die public static Connection ConnectDB() als public static Connection ConnectDB(String db)

Dann

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db, "root", "system"); 

Rufen Sie die Connection-Klasse im Konstruktor unter Verwendung des gültigen Datenbanknamens auf. ZB: conn = MySqlConnect.ConnectDB(classicmodels);

Dann für die jComboBox1ActionPerformed Ereignis die Verbindung wieder verwenden als conn = MySqlConnect.ConnectDB(jComboBox1.getSelectedItem().toString);

Dann können Sie ausgewählte db für Tabellen Bevölkerung verwenden.

Verwandte Themen