SQL Exception:can 未创建 table

SQL Exception:can not create table

当我 运行 出现此错误的代码时

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

fk_dummy_1 已经存在于 db

更改您的约束名称

"fk_dummy_1" to senName+"fk_dummy_1"

将最后一条语句改为:defaultStmt.executeUpdate();

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'