import java.awt.*;
import java.awt.event.*;
import java.sql.*;

import javax.swing.*;


public class Swing02 extends JFrame
{
        
         JTextArea ta; //
        
        Swing02()
        {
                try
               {
                        Class. forName("com.mysql.jdbc.Driver");
               }
                catch (ClassNotFoundException e1 )
               {
                        e1.printStackTrace();
               } // jdbc 드라이버 로드
               
                try
               {
                        UIManager. setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
               }
                catch (Exception e )
               {
                        e.printStackTrace();
               }
               
               setTitle( "학생관리" );
                setDefaultCloseOperation( JFrame. EXIT_ON_CLOSE);
               
               setLayout( new FlowLayout( FlowLayout. LEFT)); // 레이아웃 설정
               
               add( new JLabel( "이름 : "));
                JTextField name = new JTextField(10);
               add( name);
               
               add( new JLabel( "학과 : "));
                JTextField dept = new JTextField(10);
               add( dept);
               
               add( new JLabel( "학번 : "));
                JTextField id = new JTextField(10);
               add( id);
               
                ta = new JTextArea( "", 20, 30); // 텍스트에어리어 생성
               add( new JScrollPane(ta )); // 스크롤 적용
               
                JButton list = new JButton( "목록"); // // 'List'버튼 생성
               add( list);
                JButton insert = new JButton( "등록"); // 'Insert'버튼 생성
               add( insert);
                JButton update = new JButton( "수정"); // 'update'버튼 생성
               add( update);
                JButton delete = new JButton( "삭제"); // 'delete'버튼 생성
               add( delete);
                JButton search = new JButton( "검색"); // 'search'버튼 생성
               add( search);
               
                // ----------------------------------------------------------------------------------
               
                // 익명 클래스 이용 (이벤트 처리) -> 목록 처리
                list.addActionListener( new ActionListener()
               {
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                              List(); // 목록 갱신 메소드 호출
                       }
               });
               
                // 익명 클래스 이용2 (이벤트 처리) -> 등록 처리
                insert.addActionListener( new ActionListener()
               {      
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                               try
                              {
                                      Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
                                      Statement stmt = conn.createStatement();
                                      
                                       String n = name.getText();
                                       String d = dept.getText();
                                       String i = id.getText();
                                      
                                       // insert문 실행
                                       int result = stmt.executeUpdate("insert into student values('"+n+"','"+ d+ "','"+i +"')" );
                                      
                                       ta.setText( "");
                                       if( result == 1)
                                      {
                                              // ta.append("Insert Complete!");
                                             List(); // 목록 갱신 메소드 호출
                                      }
                                       conn.close();
                              }
                               catch(Exception ex )
                              {      
                                       // System.out.println(ex.getStackTrace());
                                       System. out.println(ex .getMessage());
                              }
                       }
               });
               
                // 익명 클래스 이용3 (이벤트 처리) -> 검색 처리
                search.addActionListener( new ActionListener()
               {
                       
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                              
                               if(( id.getText()).equals( ""))
                              {
                                       JOptionPane.showMessageDialog( null, "No ID in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else
                              {
                                       try
                                      {
                                             Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
                                             
                                             Statement stmt = conn.createStatement();
                                             
                                              String i = id.getText();

                                              // select문 실행
                                             ResultSet rs = stmt.executeQuery("select * from student where id='"+i+"'");
                                             
                                              ta.setText( ""); // 텍스트에어리어 초기화
                                             
                                              ta.append( "이름\t");
                                              ta.append( "학과\t\t");
                                              ta.append( "학번\n");
                                               ta.append( "============================================\n" );
                                             
                                              if( rs.next())
                                             {
                                                      ta.append( rs.getString( "name") + "\t" ); // 검색한 이름을 텍스트에어리어에 출력
                                                      ta.append( rs.getString( "dept") + "\t" ); // 검색한 학과을 텍스트에어리어에 출력
                                                      ta.append( rs.getString( "id") + "\n" ); // 검색한 학번을 텍스트에어리어에 출력
                                                     
                                                      id.setText( rs.getString( "id")); // 학번 텍스트필드에 학번 출력
                                                      name.setText( rs.getString( "name")); // 이름 텍스트필드에 이름 출력
                                                      dept.setText( rs.getString( "dept")); // 학과 텍스트필드에 학과 출력
                                             }
                                              rs.close();
                                              conn.close();
                                      }
                                       catch(Exception ex )
                                      {      
                                               System. out.println(ex .getStackTrace());
                                      }
                              }             
                       }             
               });
               
                // 익명 클래스 이용4 (이벤트처리) -> 수정 처리
                update.addActionListener( new ActionListener()
               {
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                               if(( id.getText()).equals( ""))
                              {
                                       JOptionPane.showMessageDialog( null, "No ID in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else
                              {
                                       int result = JOptionPane.showConfirmDialog( null, "Update?" , "Update Dialog", JOptionPane.YES_NO_OPTION);
                                      
                                       if( result == JOptionPane.YES_OPTION )
                                      {
                                              try
                                             {
                                                     Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
                                                     
                                                     Statement stmt = conn.createStatement();
                                                     
                                                      String i = id.getText();
                                                      String n = name.getText();
                                                      String d = dept.getText();
        
                                                      // update문 실행
                                                      stmt.executeUpdate( "update student set name='"+n+"', dept='"+ d+ "' where id='"+i +"'" );
                                                     
                                                      ta.setText( ""); // 텍스트에어리어 초기화
                                                      ta.setText( "Update Complete!");
                                                      JOptionPane.showMessageDialog( null, "Update Complete!", "Complete Dialog", JOptionPane.INFORMATION_MESSAGE );
               
                                                      conn.close();
                                             }
                                              catch(Exception ex )
                                             {      
                                                      System. out.println(ex .getMessage());
                                             }
                                      }
                                       else if (result == JOptionPane.NO_OPTION )
                                      {
                                             
                                      }
                              }
                       }
               });
               
                // 익명 클래스 이용5 (이벤트 처리) -> 삭제 처리
                delete.addActionListener( new ActionListener()
               {
                       
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                              
                               if(( id.getText()).equals( ""))
                              {
                                       JOptionPane.showMessageDialog( null, "No ID in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else if ((dept .getText()).equals(""))
                              {
                                       JOptionPane.showMessageDialog( null, "No Dept in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else if ((name .getText()).equals(""))
                              {
                                       JOptionPane.showMessageDialog( null, "No name in TextField!!!", "Error Dialog", JOptionPane.ERROR_MESSAGE );
                                       return; // 함수종료
                              }
                               else
                              {
                                       int result = JOptionPane.showConfirmDialog( null, "Delete?" , "Delete Dialog", JOptionPane.YES_NO_OPTION);
                                      
                                       if( result == JOptionPane.YES_OPTION )
                                      {
                                              try
                                             {
                                                     Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
                                                     
                                                     Statement stmt = conn.createStatement();
                                                     
                                                      String i = id.getText();
                                                     
                                                      // delete문 실행
                                                      stmt.executeUpdate( "delete from student where id='"+i+"'");
                                                     
                                                      ta.setText( "");
                                                      ta.setText( "Delete Complete!");
                                                      JOptionPane.showMessageDialog( null, "Delete Complete!", "Complete Dialog", JOptionPane.INFORMATION_MESSAGE );

                                                      conn.close();
                                             }
                                              catch(Exception ex )
                                             {      
                                                      System. out.println(ex .getStackTrace());
                                             }
                                      }
                                       else if (result == JOptionPane.NO_OPTION )
                                      {
                                             
                                      }
                              }                     
                       }
               });
               
                // ----------------------------------------------------------------------------------
               
               setResizable( false); // 화면 크기 고정
               setSize(350, 500); // 화면 크기 설정
               setVisible( true); // 화면 출력 설정
        }
        
         public void List()
        {
                try
               {
                       Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
                        System. out.println("JDBC Connection Complete!");
                       
                       Statement stmt = conn.createStatement();

                        // select문 실행
                       ResultSet rs = stmt.executeQuery( "select * from student"); // SQL문이 rs에 저장된다.
                       
                        ta.setText( ""); // 텍스트에어리어 초기화
                       
                        ta.append( "이름\t");
                        ta.append( "학과\t\t");
                        ta.append( "학번\n");
                        ta.append( "============================================\n" );
                       
                        while(rs .next())
                       {
                               ta.append( rs.getString( "name") + "\t" );
                               ta.append( rs.getString( "dept") + "\t" );
                               ta.append( rs.getString( "id") + "\n" );                                      
                       }
                        rs.close(); // ResultSet을 닫는다.
                        conn.close(); // Connection을 닫는다. (메모리 자원낭비 방지)
               }
                catch(Exception ex )
               {      
                        System. out.println(ex .getStackTrace());
               }
        }
        
         public static void main(String [] args)
        {
                new Swing02(); // 생성자 호출 
        }
}
 
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

import javax.swing.*;

// 독립 클래스 이용 (이벤트 처리)
/*class MyActionListener implements ActionListener
{

        @Override
        public void actionPerformed(ActionEvent e)
        {
               try
               {
                       Class.forName("com.mysql.jdbc.Driver"); // jdbc 드라이버 로드
                       Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ sampledb", "root", "1234"); // 연결
                       System.out.println("JDBC Connection Complete!");
                       
                       Statement stmt = conn.createStatement();
                       
                       // insert문 실행
                       // stmt.executeUpdate("insert into student values('천준영', '정보통신학', '2014074003')");
                       
                       // update문 실행
                       // stmt.executeUpdate("update student set id='2014000001' where name='최규식'");
                       
                       // delete문 실행
                       // stmt.executeUpdate("delete from student where id='2014000001'");
                       
                       // select문 실행
                       ResultSet rs = stmt.executeQuery("select * from student"); // SQL문이 rs에 저장된다.         
                       while(rs.next())
                       {
                              System.out.print(rs.getString("name") + "\t"); // 이름 출력
                              System.out.print(rs.getString(" dept") + "\t"); // 학과 출력
                              System.out.print(rs.getString("id") + "\n"); // 학번 출력
                       }
                       rs.close(); // ResultSet을 닫는다.
                       conn.close(); // Connection을 닫는다. (메모리 자원낭비 방지)
               }
               catch(Exception ex)
               {      
                       System.out.println(ex.getStackTrace());
               }
        }
        
}*/


public class Swing02 extends JFrame
{
        
        Swing02()
        {
               
                try
               {
                        UIManager. setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
               }
                catch (Exception e )
               {
                        e.printStackTrace();
               }
               
               setTitle( "학생관리" );
                setDefaultCloseOperation( JFrame. EXIT_ON_CLOSE);
               
               setLayout( new FlowLayout( FlowLayout. LEFT)); // 레이아웃 설정
               
               add( new JLabel( "이름 : "));
                JTextField name = new JTextField(10);
               add( name);
               
               add( new JLabel( "학과 : "));
                JTextField dept = new JTextField(10);
               add( dept);
               
               add( new JLabel( "학번 : "));
                JTextField id = new JTextField(10);
               add( id);
               
                JTextArea ta = new JTextArea( "", 5, 30); // 텍스트에어리어 생성
               add( new JScrollPane(ta )); // 스크롤 적용
               
                JButton list = new JButton( "목록"); // // 'List'버튼 생성
               add( list);
                JButton insert = new JButton( "등록"); // 'Insert'버튼 생성
               add( insert);
                JButton update = new JButton( "수정"); // 'update'버튼 생성
               add( update);
                JButton delete = new JButton( "삭제"); // 'delete'버튼 생성
               add( delete);
               
                // ----------------------------------------------------------------------------------
               
                // 익명 클래스 이용 (이벤트 처리) -> 목록 처리
                list.addActionListener( new ActionListener()
               {
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                               try
                              {
                                       Class. forName("com.mysql.jdbc.Driver"); // jdbc 드라이버 로드
                                      Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root", "1234" ); // 연결
                                       System. out.println("JDBC Connection Complete!");
                                      
                                      Statement stmt = conn.createStatement();

                                       // select문 실행
                                      ResultSet rs = stmt.executeQuery("select * from student" ); // SQL문이 rs에 저장된다.
                                      
                                       ta.setText( ""); // 텍스트에어리어 초기화
                                      
                                       ta.append( "이름\t");
                                       ta.append( "학과\t\t");
                                       ta.append( "학번\n");
                                       ta.append( "============================================\n" );
                                      
                                       while(rs .next())
                                      {
                                               /*System.out.print(rs.getString("name") + "\t"); // 이름 출력
                                              System.out.print(rs.getString(" dept") + "\t"); // 학과 출력
                                              System.out.print(rs.getString("id") + "\n"); // 학번 출력*/
                                             
                                               ta.append( rs.getString( "name") + "\t" );
                                              ta.append( rs.getString( "dept") + "\t");
                                              ta.append( rs.getString( "id") + "\n");                                     
                                      }
                                       rs.close(); // ResultSet을 닫는다.
                                       conn.close(); // Connection을 닫는다. (메모리 자원낭비 방지)
                              }
                               catch(Exception ex )
                              {      
                                       System. out.println(ex .getStackTrace());
                              }
                       }
               });
               
                // 익명 클래스 이용2 (이벤트 처리) -> 등록 처리
                insert.addActionListener( new ActionListener()
               {      
                        @Override
                        public void actionPerformed(ActionEvent e)
                       {
                               try
                              {
                                       Class. forName("com.mysql.jdbc.Driver"); // jdbc 드라이버 로드
                                      Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
                                       System. out.println("JDBC Connection Complete!");
                                      
                                      Statement stmt = conn.createStatement();
                                      
                                       String n = name.getText();
                                       String d = dept.getText();
                                       String i = id.getText();
                                      
                                       // insert문 실행
                                       int result = stmt.executeUpdate("insert into student values('"+n+"','"+ d+ "','"+i +"')" );
                                      
                                       ta.setText( "");
                                       if( result == 1)
                                      {
                                              ta.append( "Insert Complete!");
                                      }
                                       conn.close();
                              }
                               catch(Exception ex )
                              {      
                                       // System.out.println(ex.getStackTrace());
                                       System. out.println(ex .getMessage());
                              }
                       }
               });
               
                // ----------------------------------------------------------------------------------
               
               setResizable( false); // 화면 크기 고정
               setSize(350, 225); // 화면 크기 설정
               setVisible( true); // 화면 출력 설정
        }
        
         // 내부 클래스 이용 (이벤트 처리)
         /*class MyActionListener implements ActionListener
        {

               @Override
               public void actionPerformed(ActionEvent e)
               {
                       try
                       {
                              Class.forName("com.mysql.jdbc.Driver"); // jdbc 드라이버 로드
                              Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ sampledb", "root", "1234"); // 연결
                              System.out.println("JDBC Connection Complete!");
                              
                              Statement stmt = conn.createStatement();
                              
                              // insert문 실행
                              // stmt.executeUpdate("insert into student values('천준영', '정보통신학', '2014074003')");
                              
                              // update문 실행
                              // stmt.executeUpdate("update student set id='2014000001' where name='최규식'");
                              
                              // delete문 실행
                              // stmt.executeUpdate("delete from student where id='2014000001'");
                              
                              // select문 실행
                              ResultSet rs = stmt.executeQuery("select * from student"); // SQL문이 rs에 저장된다.          
                              while(rs.next())
                              {
                                      System.out.print(rs.getString("name") + "\t"); // 이름 출력
                                      System.out.print(rs.getString(" dept") + "\t"); // 학과 출력
                                      System.out.print(rs.getString("id") + "\n"); // 학번 출력
                              }
                              rs.close(); // ResultSet을 닫는다.
                              conn.close(); // Connection을 닫는다. (메모리 자원낭비 방지)
                       }
                       catch(Exception ex)
                       {      
                              System.out.println(ex.getStackTrace());
                       }
               }
               
        }*/
        
         public static void main(String [] args)
        {
                new Swing02(); // 생성자 호출 
        }
}

 

 
import java.awt.*;
import java.sql.*;

import javax.swing.*;

public class Swing02 extends JFrame
{
        
        Swing02()
        {
               
                try
               {
                        UIManager. setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
               }
                catch (Exception e )
               {
                        e.printStackTrace();
               }
               
               setTitle( "입력창");
                setDefaultCloseOperation( JFrame. EXIT_ON_CLOSE);
               
               setLayout( new FlowLayout( FlowLayout. LEFT)); // 레이아웃 설정
               
               add( new JLabel( "이름 : "));
               add( new JTextField(10));
               add( new JLabel( "학과 : "));
               add( new JTextField(10));
               add( new JLabel( "학번 : "));
               add( new JTextField(10));
               
               setSize(350, 200);
               setVisible( true);
        }
        
         public static void main(String [] args)
        {
                new Swing02(); // 생성자 호출
               
                try
               {
                        Class. forName("com.mysql.jdbc.Driver"); // jdbc 드라이버 로드
                       Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/sampledb" , "root" , "1234" ); // 연결
                        System. out.println("JDBC Connection Complete!");
                       
                       Statement stmt = conn.createStatement();
                       
                        // insert문 실행
                        // stmt.executeUpdate("insert into student values('천준영', '정보통신학', '2014074003')");
                       
                        // update문 실행
                        // stmt.executeUpdate("update student set id='2014000001' where name='최규식'");
                       
                        // delete문 실행
                        // stmt.executeUpdate("delete from student where id='2014000001'");
                       
                        // select문 실행
                       ResultSet rs = stmt.executeQuery( "select * from student"); // SQL문이 rs에 저장된다.         
                        while(rs .next())
                       {
                               System. out.print(rs .getString("name") + "\t"); // 이름 출력
                               System. out.print(rs .getString("dept") + "\t"); // 학과 출력
                               System. out.print(rs .getString("id") + "\n"); // 학번 출력
                       }
                        rs.close(); // ResultSet을 닫는다.
                        conn.close(); // Connection을 닫는다. (메모리 자원낭비 방지)
               }
                catch(Exception e )
               {      
                        System. out.println(e .getStackTrace());
               }
        }
}