日食中如何忽略'表已存在'错误

问题描述 投票:0回答:1

我在eclipse中有代码为mysql数据库创建表,但是在初始创建后,它抛出错误“表已存在”。有没有一种方法可以忽略此错误,以便在执行代码时它不会出现在控制台中?我不确定是否需要对代码做某事,或者是否需要在Eclipse中对其进行更改,但是如果需要的话,我在下面包括了我的代码

package project_files;
import java.sql.*;

import javax.swing.JOptionPane;

public class database {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/userdatabase";

   //  Database credentials
   static final String USER = "root";
   static final String PASS = "pass1234";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{


      //STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");

      //STEP 4: Execute a query
      System.out.println("Creating table in given database...");
      stmt = conn.createStatement();



      String sql = "CREATE TABLE review " +
                   "(video_name VARCHAR(45) not NULL, " +
                  " review_comments VARCHAR(45), " + 
                   " review_star VARCHAR(45), " +       
                   " PRIMARY KEY ( video_name ))"; 

      String sql1= "CREATE TABLE user " +
              "(FirstName VARCHAR(45) not NULL, " +
             " LastName VARCHAR(45), " + 
              " City VARCHAR(45), " +   
              " DOB VARCHAR(45), " +
              " Phone Number BIGINT(20), " +
              " Email VARCHAR(45), " +
              " PRIMARY KEY ( Email ))"; 

      String sql2= "CREATE TABLE video " +
              "(video_name VARCHAR(45) not NULL, " +
             " video_description VARCHAR(45), " + 
              " video_city VARCHAR(45), " +   
              " video_tags VARCHAR(45), " +
              " video_subject VARCHAR(45), " +
              " PRIMARY KEY ( video_name ))"; 

      stmt.executeUpdate(sql);
      stmt.executeUpdate(sql1);
      stmt.executeUpdate(sql2);

      System.out.println("Created table in given database...");
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   JOptionPane.showMessageDialog(null, "Tables created successfully");
}//end main
}//end JDBCExample
mysql eclipse jdbc
1个回答
1
投票

您可以使用IF NOT EXISTS

如果表存在,防止发生错误。但是,没有验证现有表的结构与CREATE TABLE语句指示的结构相同。

IF NOT EXISTS
© www.soinside.com 2019 - 2024. All rights reserved.