gpt4 book ai didi

mysql - 如何忽略eclipse中的 'table already exists'错误

转载 作者:行者123 更新时间:2023-11-29 09:29:20 24 4
gpt4 key购买 nike

我在 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

最佳答案

您可以使用IF NOT EXISTS :

Prevents an error from occurring if the table exists. However, there is no verification that the existing table has a structure identical to that indicated by the CREATE TABLE statement.

CREATE TABLE IF NOT EXISTS review(...);

关于mysql - 如何忽略eclipse中的 'table already exists'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59038514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com