⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mysqljava.java

📁 java写的一个针对MSYQL数据库的程序,具有增加,删除查找数据等功能
💻 JAVA
字号:

// This program displays the ResultSet returned by a
// query on the Books database.
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class MysqlJava extends JFrame {
   // java.sql types needed for database processing
   private Connection connection;
   private Statement statement;
   private ResultSet resultSet;
   private ResultSetMetaData rsMetaData;
   private String tableName;
   // javax.swing types needed for GUI
   private JTable table;
   private JTextArea inputQuery;
   private JButton submitQuery;
    private JButton findName, addName,
                   updateName, clear, help,set_option;
   //private SetOption option;
   private JPopupMenu pupupMenu;
   private JRadioButtonMenuItem items[];
   private String str1,query_result;
   public MysqlJava() 
   {   
      super("数据库接口类");
      // SetOption option=new SetOption();
    final JPopupMenu popupMenu=new JPopupMenu();//生成弹出菜单
      
      tableName=new String("authorisbn");
                // Load the driver to allow connection to the database
      try {

 Class.forName("org.gjt.mm.mysql.Driver");
 connection=DriverManager.getConnection("jdbc:mysql://localhost/books","root","761222");
               } 
      catch ( ClassNotFoundException cnfex ) {
         System.err.println( 
            "Failed to load JDBC/ODBC driver." );
         cnfex.printStackTrace();
         System.exit( 1 );  // terminate program
      }
      catch ( SQLException sqlex ) {
         System.err.println( "Unable to connect" );
         sqlex.printStackTrace();
         System.exit( 1 );  // terminate program
      }
      str1=new String("select * from ");
      String query_resutl=new String();
      query_result=str1+tableName;
      
    //  tableName="select * from "+tableName;
      inputQuery =
         new JTextArea( query_result,4, 30 );
   
          Container c = getContentPane();
      c.setLayout( new BorderLayout() );
        c.add( new JScrollPane( inputQuery), 
                    BorderLayout.NORTH);
       JPanel topPanel = new JPanel();
      
      topPanel.setLayout( new GridLayout(1,8));
       
      set_option=new JButton("option");
        set_option.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e ) 
            {
              // SetOption option=new SetOption();
               //tableName=option.getTableName();
               //System.out.println(tableName);
               Object[] obj1={"authorisbn","authors","publishers","titles"};
               Object selectedValue=JOptionPane.showInputDialog(null,"选择数据表","请选择要操作的数据表",
                JOptionPane.INFORMATION_MESSAGE,null,obj1,obj1[0]);
                tableName=selectedValue.toString();
                query_result=str1+tableName;
               
                Container c = getContentPane();
                c.remove(2);
                  inputQuery.setText(query_result);
             inputQuery.repaint();
            
               getTable();
             }
         }   
      );
      
     // set_option.addActionListener(new SetOption());
      topPanel.add(set_option);
      submitQuery = new JButton( "Display" );
      topPanel.add(submitQuery);
      submitQuery.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e ) 
            {
            //	inputQuery.repaint();
            	Container c = getContentPane();
                c.remove(2);
               getTable();
            }
         }   
      );
      findName = new JButton( "Find" );
    //  findName.addActionListener( new FindRecord( c, s, t ) );
      topPanel.add( findName );

      addName = new JButton( "Add" );
     // addName.addActionListener( new AddRecord( c, s, t ) );
      topPanel.add( addName );
 /*          addName.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e ) 
            {
               deleteTable();
            }
         }   
      );
      */
      updateName = new JButton( "Update" );
     // updateName.addActionListener(
      //   new UpdateRecord( c, s, t ) );
      topPanel.add( updateName );
      
      clear = new JButton( "Clear" );
    // clear.addActionListener( new ClearFields( s ) );
      topPanel.add( clear );
      
      help = new JButton( "Help" );
   //   help.addActionListener( new Help( t ) );
   
      topPanel.add( help );
       c.add( topPanel, BorderLayout.SOUTH);
     //菜单操作 
      //topPanel.add( submitQuery, BorderLayout.SOUTH );
     // JMenu fileMenu=new JMenu("file");
   /*    JMenu fileMenu = new JMenu( "File" );
      fileMenu.setMnemonic( 'F' );
      JMenuItem aboutItem = new JMenuItem( "About..." );
      aboutItem.setMnemonic( 'A' );
      aboutItem.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               JOptionPane.showMessageDialog(null,"AA");
            }
         }
      );
      fileMenu.add( aboutItem );

      JMenuItem exitItem = new JMenuItem( "Exit" );
      exitItem.setMnemonic( 'x' );
      exitItem.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e )
            {
               System.exit( 0 );
            }
         }
      );
      fileMenu.add( exitItem );
      JMenuBar bar=new JMenuBar();
      setJMenuBar(bar);
      bar.add(fileMenu);
      topPanel.add(bar);
     
      //c.add(bar);
     
      
      */
      //弹出式菜单
      
   /*   ItemHandler handler=new ItemHandler();
      String tables[]={"authorisbn","authors","publisher","titles"};
      ButtonGroup tableGroup=new ButtonGroup();
      items=new JRadioButtonMenuItem[4];
      for (int i=0;i<items.length;i++)
      {
      items[i]=new JRadioButtonMenuItem(tables[i]);
     
      popupMenu.add(items[i]);
      tableGroup.add(items[i]);
      items[i].addActionListener(handler);
    }
       addMouseListener(
         new MouseAdapter() {
            public void mousePressed( MouseEvent e )
               { checkForTriggerEvent( e ); } 

            public void mouseReleased( MouseEvent e )
               { checkForTriggerEvent( e ); } 

            private void checkForTriggerEvent( MouseEvent e )
            {
               if ( e.isPopupTrigger() ) 
                  popupMenu.show( e.getComponent(),
                                  e.getX(), e.getY() );               
            }
         }
      ); 
     */
        getTable();
           
      
      setSize( 400, 400 );
      show();
   }
  
 /* private class ItemHandler implements ActionListener {
      public void actionPerformed( ActionEvent e )
      {
         // determine which menu item was selected
         for ( int i = 0; i < items.length; i++ )
            if ( e.getSource() == items[ i ] ) {
            	
               tableName=items[i].getText();
             //  System.out.println(tableName);
              // repaint();
              // return;
              getTable();
            }
      }
   }
  private void showMenu(JPopupMenu  p)
  {
  	
  //JOptionPane.showMessageDialog(null,"aa");
  p.show();
  
}
*/
   private void deleteTable()
   {
   	try {
        //String query = inputQuery.getText();
               
         String query = inputQuery.getText();
         //inputQuery.repaint();
         statement = connection.createStatement();
 
      int    result = statement.executeUpdate(query);    
       
     if (result>0)
      JOptionPane.showMessageDialog(null,"success");
      else
      JOptionPane.showMessageDialog(null,"failed");
        statement.close();

        
      }
      catch ( SQLException sqlex ) {
      	
         sqlex.printStackTrace();
      }
   }
 
   private void getTable()
   {
      try {
        //String query = inputQuery.getText();
            // table.repaint();
           
       String query = inputQuery.getText();
      
         statement = connection.createStatement();
 
         resultSet = statement.executeQuery( query );        
   
         displayResultSet( resultSet );

        
      }
      catch ( SQLException sqlex ) {
      	
         sqlex.printStackTrace();
      }
   }

   private void displayResultSet( ResultSet rs )
      throws SQLException
   {
   	//table.repaint();
   	
      
      
      // position to first record
      boolean moreRecords = rs.next();  
       
      // If there are no records, display a message
      if ( ! moreRecords ) {
         JOptionPane.showMessageDialog( this, 
            "ResultSet contained no records" );
         setTitle( "No records to display" );
         return;
      }

      Vector columnHeads = new Vector();
      Vector rows = new Vector();

      try {
         // get column heads
         ResultSetMetaData rsmd = rs.getMetaData();
      
         for ( int i = 1; i <= rsmd.getColumnCount(); ++i ) 
            columnHeads.addElement( rsmd.getColumnName( i ) );
 
         // get row data
         do {
            rows.addElement( getNextRow( rs, rsmd ) ); 
         } while ( rs.next() );

         // display table with ResultSet contents
         table = new JTable( rows, columnHeads );
         
         JScrollPane scroller = new JScrollPane( table );
        Container c = getContentPane();

      //c.remove( 0);
      //  scroller.repaint();
     
         c.add( scroller, BorderLayout.CENTER );
        //c.update();
        c.repaint();
        c.validate();
      }
      catch ( SQLException sqlex ) {
         sqlex.printStackTrace();
      }
   // table.repaint();
   }

   private Vector getNextRow( ResultSet rs, 
                              ResultSetMetaData rsmd )
       throws SQLException
   {
      Vector currentRow = new Vector();
      
      for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
         switch( rsmd.getColumnType( i ) ) {
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                  currentRow.addElement( rs.getString( i ) );
               break;
            case Types.INTEGER:
                  currentRow.addElement( 
                     new Long( rs.getLong( i ) ) );
               break;
            
                 
            case Types.CHAR:
                  currentRow.addElement(rs.getString(i));
                 break;

                              default: 
               System.out.println( "Type was: " + 
                  rsmd.getColumnTypeName( i ) );
         }
      
      return currentRow;
   }

   public void shutDown()
   {
      try {
         connection.close();
      }
      catch ( SQLException sqlex ) {
         System.err.println( "Unable to disconnect" );
         sqlex.printStackTrace();
      }
   }

   public static void main( String args[] ) 
   {
      final MysqlJava  app = 
         new MysqlJava ();

      app.addWindowListener( 
         new WindowAdapter() {
            public void windowClosing( WindowEvent e ) 
            {  
               app.shutDown();
               System.exit( 0 );
            }
         }
      );
   }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -