简体   繁体   中英

DB creation and deletion in mysql

I use the following code to create new Database. If the given Database name is same as existing Database name means the existing Database need to be deleted else the new data base need to be created with the given name. I have error in creating new database.

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/vijay1","root","root");
            try{

                Statement st = con.createStatement();
                                String database=txt.getText();
                                st.executeUpdate("DROP DATABASE IF EXISTS "+database);
                                JOptionPane.showMessageDialog(frame,"EXISTING DATABASE DELETED");
                                 st.executeUpdate("CREATE DATABASE "+database);
                 JOptionPane.showMessageDialog(frame,"DATABASE CREATED");
            }
            catch (SQLException s){
                System.out.println("SQL statement is not executed!");
            }
        }
        catch (Exception ea){
                   ea.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
        new Main();
    }
}

Try this as your inner try block, hope this will help.

   try
   {
     String database=txt.getText();
     String query = "if exists(select * from sys.databases where (name = ?))"
                     + "drop database " + database
                     + "create database " + database;
     PreparedStatement statement = con.prepareStatement(query);              
     statement.setString(1, database);


     statement.executeUpdate();
     JOptionPane.showMessageDialog(frame,"EXISTING DATABASE DELETED");

     JOptionPane.showMessageDialog(frame,"DATABASE CREATED");
  }

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM