在运行时检查数据库名称并创建数据库

编程入门 行业动态 更新时间:2024-10-26 04:28:07
本文介绍了在运行时检查数据库名称并创建数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个JTextfield用于获取要创建的数据库名称,还有一个JButton用于以挥杆形式执行数据库创建操作.问题是,当我将值提供给文本字段并单击按钮时,它需要检查整个数据库,如果数据库存在的名称与我们为新数据库提供的名称相同.这意味着需要删除现有数据库,并为新数据库接受给定名称.这是我的代码.

I have one JTextfield for getting the database name to be created and JButton for performing database creation action in my swing form. The problem is when I give the value to the textfield and click the button it needs to check the entire database if the database exists with the same name that we gave to the new database. This means the existing database need to be deleted and the given name to be accepted for the new database. Here is my code.

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

推荐答案

在create database之前,请使用:

DROP DATABASE IF EXISTS db_name;

,也不必检查它是否存在.检查 MySQL DROP DATABASE语法.

and don't bother checking whether it exists or not. Check MySQL DROP DATABASE Syntax.

更多推荐

在运行时检查数据库名称并创建数据库

本文发布于:2023-11-30 21:37:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651544.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库   名称

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!