Search code examples
javamysqljdbcsqlexception

SQL Exception:can not create table


when i run the code this error follows

Exception in thread "main" java.sql.SQLException: Can't create table 'Sensors_db.one' (errno: 121)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
    at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1362)
    at sensordev.SensorDev.sensorPage(SensorDev.java:283)
    at sensordev.SensorDev.main(SensorDev.java:893)

following is my my code

String type = "37";
        String senName = "one";
        String query;
        switch(type){
            case "37":{

                query = "CREATE TABLE IF NOT EXISTS `"+ senName +"` ("
                        + "  `Name` VARCHAR(45) NOT NULL,"
                        + "  `State` VARCHAR(45) NOT NULL,"
                        + "  `Time` TIME NOT NULL,"
                        + "  PRIMARY KEY (`Time`, `State`),"
                        + "  INDEX `fk_dummy_1_idx` (`Name` ASC),"
                        + "  CONSTRAINT `fk_dummy_1`"
                        + "    FOREIGN KEY (`Name`)"
                        + "    REFERENCES `Sensors_db`.`sensorInfo` (`SName`)"
                        + "    ON DELETE NO ACTION"
                        + "    ON UPDATE NO ACTION);";
                defaultStmt = conn.prepareStatement(query);
                 defaultStmt.execute();

'conn' is my database instance and 'defaultStmt' is a PreparedStatement


Solution

  • err 121 indicates that the constraint name is already used. Change your constraint name. Constraint name should be unique within your database.

    To see if the constraint already exists.

    SELECT
        table_name
    FROM
        information_schema.table_constraints
    WHERE
        constraint_type = 'FOREIGN KEY'
        AND table_schema = DATABASE() AND
        constraint_name = 'fk_dummy_1'