Search code examples
javaswingjtextfield

How to display any result from mysql into TextArea Java


I already know the codes to display the results from table like select * from and bla bla. But I want to display ANY result from mysql to netbeans. For ex.-> If user says "show databases", it should display databases in textarea and same is for tables. I mean, no matter whatever user wants to see, whether its seeing the table or databases or columns or what, the result should appear in textarea. And i possibly cant go on writing commands for each of these actions since there are so many possibilities. So please, is there any way to display all the results from mysql into textarea in java? Thanks.

EDIT: Well... I got netbeans (yeah i am a little new to this stuff) and so far this is my code. I want the result to be displayed in a text area. Here is coding for frame in which the textarea exists where i want results to appear- >

package MYSQL_GUI;
import static MYSQL_GUI.Frame1.j;
import static MYSQL_GUI.Frame1.k;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class CustComm extends javax.swing.JFrame {

    /**
     * Creates new form CustComm
     */
    public CustComm() {
        initComponents();
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
}

    /**
     * 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() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea3 = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("MySQL Custom Command Editor");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Enter Custom Commands Below");

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Execute Command(s)");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancel");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextArea2.setEditable(false);
        jTextArea2.setColumns(20);
        jTextArea2.setLineWrap(true);
        jTextArea2.setRows(2);
        jTextArea2.setText("!!Separate commands by writing each command in new line with proper syntax just like in MySQL.");
        jTextArea2.setFocusable(false);
        jTextArea2.setHighlighter(null);
        jTextArea2.setOpaque(false);
        jScrollPane2.setViewportView(jTextArea2);

        jLabel2.setText("Enter Command(s) below:");

        jTextArea3.setEditable(false);
        jTextArea3.setColumns(10);
        jTextArea3.setRows(5);
        jScrollPane3.setViewportView(jTextArea3);

        jLabel3.setText("Command Outputs:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
                                    .addComponent(jScrollPane1)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(247, 247, 247)
                                .addComponent(jLabel2)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(40, 40, 40))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(222, 222, 222)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(122, 122, 122)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(95, 95, 95)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String x = jTextArea1.getText();
        Scanner scanner = new Scanner(x);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  if(line.contains("use ")){
      if(line.contains("use ")&&!GlobalParams.usedb){
         JOptionPane.showMessageDialog(this, "Please use the Program to select database.");   
        }
      else{
      try{
       Class.forName("java.sql.DriverManager");
       Connection con = (Connection)
       DriverManager.getConnection("jdbc:mysql://localhost:"+GlobalParams.portvar+"/",GlobalParams.uservar, GlobalParams.passvar);
       Statement stmnt = (Statement) con.createStatement();
        String query = line;
        stmnt.executeUpdate(query);
        JOptionPane.showMessageDialog(this, "Commands Executed Successfully");
        this.dispose();}
      catch(Exception e){
        JOptionPane.showMessageDialog(this,e.getMessage());
    }
  }}
  if(line.contains("create table ")){
      if(line.contains("create table ")&&!GlobalParams.usedb){
         JOptionPane.showMessageDialog(this, "You can only create tables and manipulate them in next section");   
        }
      else{
      try{
       Class.forName("java.sql.DriverManager");
       Connection con = (Connection)
       DriverManager.getConnection("jdbc:mysql://localhost:"+GlobalParams.portvar+"/",GlobalParams.uservar, GlobalParams.passvar);
       Statement stmnt = (Statement) con.createStatement();
        String query = line;
        stmnt.executeQuery("use "+GlobalParams.dbvar);
        stmnt.executeUpdate(query);
        JOptionPane.showMessageDialog(this, "Commands Executed Successfully");
        this.dispose();}
      catch(Exception e){
        JOptionPane.showMessageDialog(this,e.getMessage());
    }
  }}
        else{
  try{
       Class.forName("java.sql.DriverManager");
       Connection con = (Connection)
       DriverManager.getConnection("jdbc:mysql://localhost:"+GlobalParams.portvar+"/",GlobalParams.uservar, GlobalParams.passvar);
       Statement stmnt = (Statement) con.createStatement();
        String query = line;
        stmnt.executeUpdate(query);
        JOptionPane.showMessageDialog(this, "Commands Executed Successfully");
        this.dispose();}

    catch(Exception e){
        JOptionPane.showMessageDialog(this,e.getMessage());
    }}}
try{
        Class.forName("java.sql.DriverManager");
        Connection con = (Connection)
        DriverManager.getConnection("jdbc:mysql://localhost:"+GlobalParams.portvar+"/",""+k,""+j);
        Statement stmnt = (Statement) con.createStatement();
        String query = "show databases";
        ResultSet rs = stmnt.executeQuery(query);
        while (rs.next()){
        String db = rs.getString("Database");
        }
}
    catch(Exception e){
        JOptionPane.showMessageDialog(this,e.getMessage());
    }
        GlobalParams.usedb=false;
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
int dialogResult = JOptionPane.showConfirmDialog (this, "You may loose your commands if you did not execute them. Are you sure you want to Proceed?");
if(dialogResult == JOptionPane.YES_OPTION){dispose();}
else{};
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        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(CustComm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CustComm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CustComm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CustComm.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 CustComm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    public static javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextArea jTextArea3;
    // End of variables declaration                   
}

This is coding for only one frame where i want to have my purpose. Here is coding of my complete main frame, just in case you need it (I dont think you will but still....)-> http://pastebin.com/ewnEpt8P# Its too long so I cant post here.


Solution

  • Although non-trivial, the usual approach is to consult an instance of your driver's implementation of ResultSetMetaData. You can search for a tutorial that you like, but I found JDBCXYDataset, cited here, to be fairly accessible.

    Adddendum: I want to create a virtual MySQL.

    There's no easy way to do this without a fair amount of code that uses DatabaseMetaData to interrogate the database's data dictionary. Some examples are cited here.