在mysql中创建和删除数据库

时间:2011-12-19 06:43:52

标签: java mysql

我使用以下代码创建新数据库。如果给定的数据库名称与现有数据库名称相同,则表示需要删除现有数据库,否则需要使用给定名称创建新数据库。我在创建新数据库时遇到错误。

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();
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将此作为内部尝试块,希望这会有所帮助。

   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");
  }

此致