2013-10-03 2 views
-1

select * from 및 bla bla와 같은 테이블의 결과를 표시하는 코드는 이미 알고 있습니다. 하지만 mysql에서 netbeans에 대한 결과를 표시하고 싶습니다. 예를 들어 -> 사용자가 "데이터베이스 표시"라고 말하면 데이터베이스는 텍스트 영역에 표시해야하며 테이블에 대해서도 마찬가지입니다. 내 말은, 사용자가 무엇을보고 싶어하든 테이블이나 데이터베이스 또는 열을 보는 지 또는 결과가 텍스트 영역에 나타나야하는지 여부입니다. 그리고 나는 가능성이 너무 많기 때문에 이러한 행동 각각에 대해 명령을 쓰지 않을 수 있습니다. 그래서, mysql의 모든 결과를 java의 textarea에 표시 할 수있는 방법이 있습니까? 감사합니다. .mysql에서 TextArea Java에 결과를 표시하는 방법

편집 : 글쎄 ... 나는 넷빈 (예, 나는이 물건에 조금 익숙하지 않다)을 가지고 있고, 지금까지 이것은 나의 코드이다. 결과를 텍스트 영역에 표시하고 싶습니다. 나는 결과가 난 내 목적을 갖고 싶어하는 곳은 단 하나의 프레임에 대한 코딩되어

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     
} 

된 것으로 나타> 원하는 곳 여기에 텍스트 영역이 존재하는 프레임을 코딩한다. 여기 내 전체 메인 프레임을 코딩하고 있습니다. 당신이 필요로 할 때를 대비해 (나는 아직도 당신이 생각할 필요는 없지만 ....) ->http://pastebin.com/ewnEpt8P# 너무 길기 때문에 여기에 게시 할 수 없습니다.

+2

짧은 대답 : 예. 긴 대답 : 예,하지만 당신은 몇 가지 일을해야합니다. 이 목표를 향해 무엇을 했습니까? – Makoto

+0

나는 이것을 위해 필요한 "것들"을 할 준비가되어있다. 나는 구글을 찾았지만,별로 도움이되지 못했다. 그러니 제게 해결책을주십시오. – Hoobla

+1

나는 당신을 위해 그것을 철저히 쓰지 않을 것입니다. 구현 한 코드가 있습니까? 질문을 던지면 크게 도움이 될 것입니다. 점프 포인트를 얻을 수 있습니다. – Makoto

답변

1

평범한 방법은 운전자가 구현 한 ResultSetMetaData의 인스턴스를 참조하는 것입니다. 당신은 search for a tutorial을 좋아할 수 있지만, JDBCXYDataset, here이 상당히 쉽게 접근 할 수있는 것으로 나타났습니다.

추가 : 가상 MySQL을 만들고 싶습니다.

DatabaseMetaData을 사용하여 데이터베이스의 데이터 사전을 조회하는 상당한 양의 코드가 없으면 쉽게이 작업을 수행 할 수 없습니다. 몇 가지 예가 here입니다.

+0

그 정확하게 내가 찾고있는 것이 아니라 나는 많은 새로운 것을 배웠다. 그래서 고마워. 이제 내가 찾고있는 것 -> 귀하의 링크는 select * from과 bla bla를 사용하여 테이블에서 결과를 얻는 방법과 다른 것들을 제공합니다. 하지만 내가 원한 것은 명령이 무엇이든 관계없이 출력을 텍스트 필드에 표시해야한다는 것입니다. 이것은 데이터베이스 관련 명령뿐만 아니라 테이블 조작 명령을 의미합니다. 이후 모든 명령에 대해 "ifs"를 지정하지 않으므로 오류가 있어도 자동으로 결과 또는 mysql에 의해 주어진 출력을 얻으려면 몇 가지 코드가 필요합니다.간단히 말해 가상 MySQL을 만들고 싶습니다. – Hoobla

+0

나는 정교하게 노력했다. – trashgod

+0

나에게 기초를 제공 해주셔서 감사합니다. 그것에 작동합니다. – Hoobla

관련 문제