This question already has answers here:
ERROR: Error 1005: Can't create table (errno: 121)
                                
                                    (8个答案)
                                
                        
                                4年前关闭。
            
                    
当我运行代码时,出现此错误

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)


以下是我的代码

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”是我的数据库实例,“ defaultStmt”是PreparedStatement

最佳答案

err 121表示约束名称已被使用。更改您的约束名称。约束名称在数据库中应该是唯一的。

查看约束是否已经存在。

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

关于java - SQL异常:无法创建表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32839886/

10-12 00:22