2011-12-17 86 views
0

我有一個JTextfield用於獲取要創建的數據庫名稱,JButton用於以我的swing形式執行數據庫創建操作。問題是,當我給文本字段賦值時,如果數據庫存在與我們給新數據庫相同的名稱,單擊它需要檢查整個數據庫的按鈕。這意味着需要刪除現有的數據庫,併爲新數據庫接受給定的名稱。這是我的代碼。在運行時檢查數據庫名稱和創建數據庫

package db1; 


    import java.awt.*; 
    import java.awt.event.*; 
    import javax.swing.*; 
    import java.io.*; 
    import java.sql.*; 
    import java.sql.Connection; 
    import java.sql.DriverManager; 
    import java.sql.SQLException; 
    import java.sql.Statement; 

    public class Main implements ActionListener 
    { 
     JTextField txt; 
     JButton create; 
     JFrame frame; 
     JPanel panel; 
     JOptionPane jop; 
     //Font font = UIManager.getFont("txt.font"); 
     public Main() 
     { 
      frame=new JFrame(); 
      panel=new JPanel(); 
      txt=new JTextField(10); 
      create=new JButton("create"); 
      create.setBounds(20, 200, 50, 40); 

     panel.add(txt); 
     panel.add(create); 
     create.addActionListener(this); 
     frame.add(panel); 



      // n.getContentPane().add(new textf()); 
      frame.setSize(440,310); 
      frame.setVisible(true); 

     } 
     public void actionPerformed(ActionEvent e) 
     { 
     Connection con = null; 
      try{ 
       Class.forName("com.mysql.jdbc.Driver"); 
       con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay","root","root"); 
       try{ 

            String database=txt.getText(); 
            Statement st = con.createStatement(); 
            String check=null; 
            ResultSet rs = con.getMetaData().getCatalogs(); 
            while (rs.next()) { 
            // System.out.println("" + rs.getString("TABLE_CAT")); 
            check=rs.getString("TABLE_CAT"); 
            System.out.println(check); 

            if(database.equals(check)) {I NEED CODE HERE} 
            { 
             String query = "DROP DATABASE"+check; 
             st.executeUpdate(query); 
            } 
            else{ 
            st.executeUpdate("CREATE DATABASE "+database); 
        JOptionPane.showMessageDialog(frame,"DATA BASE IS CREATED"); 

             } 


           } 
         } 

       catch (SQLException s) 
          { 
        System.out.println(s); 
           //JOptionPane.showMessageDialog(frame,"DATA BASE IS already exist"); 
       } 
      } 
      catch (Exception ea){ 
         ea.printStackTrace(); 
      } 
     } 


     public static void main(String[] args) 
     { 
      new Main(); 

     } 


    } 

回答

1

create database之前只需使用:

DROP DATABASE IF EXISTS db_name; 

也懶得檢查它是否存在與否。檢查MySQL DROP DATABASE Syntax