无法通过python将外键添加到mysql表中

时间:2016-03-02 16:28:03

标签: python mysql

我正在尝试在MySQL中创建三个表,这里是代码

TABLES['MACHINE'] = (
    "CREATE TABLE `MACHINE` ("
    "  `id` int NOT NULL AUTO_INCREMENT,"
    "  `x` int NOT NULL ,"
    "  `y` int NOT NULL,"
    "  `machineid` varchar(255) NOT NULL,"
    "  `sitename` varchar(255) NOT NULL,"
    "  `version_PK` int NOT NULL,"
    "  `type` varchar(255) NOT NULL,"
    "   `r` varchar(255) NOT NULL,"
    "  `s` varchar(255) NOT NULL,"
    "  `re` varchar(255) NOT NULL,"
    "  `dd` DATETIME NOT NULL,"
    "  `country` varchar(255) NOT NULL,"
    "  `latitude` float  ,"
    "  `longitude` float ,"
    "  PRIMARY KEY (`id`),"
    " unique key (`machineid`)"
    ") ENGINE=InnoDB")
TABLES['JOB'] = (
    "CREATE TABLE `JOB` ("
    "  `id` int NOT NULL AUTO_INCREMENT,"
    "  `machine_id` varchar(255) NOT NULL,"
    "  `sl` int NOT NULL,"
    "  `sc` int NOT NULL,"
    "  `vercsion_PK` int NOT NULL,"
    "  PRIMARY KEY (`id`),"
    "  CONSTRAINT `JOB_1` FOREIGN KEY (`machine_id`) "
    "        REFERENCES `MACHINE` (`machineid`) ON DELETE CASCADE"
    ") ENGINE=InnoDB")

TABLES['SCAN_PASS'] = (
    "CREATE TABLE `SCAN_PASS` ("
    "  `id` int NOT NULL AUTO_INCREMENT,"
    "  `job_id` int NOT NULL,"
    "  `dates` DATETIME NOT NULL,"
    "  `pass` int NOT NULL,"
    "  `rawdata` varchar(255) NOT NULL,"
    "  `units` varchar(255) NOT NULL,"
    "  `afterpass` int NOT NULL,"
    "  `version_PK` int NOT NULL,"
    "  PRIMARY KEY (`id`),"
    "  CONSTRAINT `SCAN_1` FOREIGN KEY (`job_id`) "
    "        REFERENCES `JOB` (`id`) ON DELETE CASCADE"
    ") ENGINE=InnoDB")


for name, ddl in TABLES.iteritems():
    cursor.execute(ddl)

cursor.close()
db.close()

问题是我在运行代码时出现此错误“IntegrityError:(1215,'无法添加外键约束')”

令我困惑的是,当我将第三个表的名称更改为除scan_pass之外的任何其他内容时。一切似乎都很好。 这段代码生成数据库,然后创建这些表,我只是没有包含生成数据库的代码。 MySQL服务器中没有其他表在任何其他数据库中具有相同名称“scan_pass”。 为什么它只是在表的名称是“scan_pass”时才会抱怨?我真的需要一个有这个名字的桌子。 感谢您提前提供任何帮助

0 个答案:

没有答案