Reputation: 67
I have code in eclipse that creates tables for mysql database, but after the initial creation it throws the error 'table already exists'. Is there a way to ignore this error so that it doesn't appear in the console when executing the code? I'm not sure if to do so I have to do something to my code or if its something to be changed in Eclipse, but in case I included my code below if need be
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
Upvotes: 0
Views: 1410
Reputation: 175874
You could use 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(...);
Upvotes: 3