Ben Ben - 1 month ago 8
Java Question

I trying to create a table in MySQL database using JDBC

I'm trying to create a table in my MySQL database. Here's my code:

//Table
public static void createTable() throws Exception
{
try {
Connection conn = getConnection();
PreparedStatement create = conn.prepareStatement("CREATE TABLE IF NOT EXIST registration(id int NOT NULL AUTO_INCREMENT,first_name varchar(45),last_name(45),email varchar(320),password varchar(50),PRIMARY KEY(id))");
create.executeUpdate();
}
catch(Exception e) {
System.out.println(e);
}
finally {
System.out.println("System Updated");
};
}
//End of Table


This is the error I'm getting


com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EXIST registration(id int NOT NULL AUTO_INCREMENT,first_name varchar(45),last_name(45),email var' at line 1

Answer

There are two things wrong with this query:

  1. It should be if not exits, with an "s" at the end.
  2. The last_name column is missing a type (presumably varchar?)

Put it all together, and your SQL should look like:

CREATE TABLE IF NOT EXISTS -- First issue
registration
(id INT NOT NULL AUTO_INCREMENT,
 first_name VARCHAR(45),
 last_name  VARCHAR(45), -- Second issue
 email VARCHAR(320),
 password VARCHAR(50),
 PRIMARY KEY(id)
)
Comments