我有一个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();
}
}
答案 0 :(得分:2)