- 论坛徽章:
- 0
|
最近在用SQLAlchemy进行数据库编程,我用如下代码新建表并添加主键:
class Admin(db.Model):
__tablename__ = 'admin_info'
admin_id = db.Column("admin_id", db.String(20), primary_key=True)
key_id = db.Column("key_id", db.INT, primary_key=True)
key_comment = db.Column("key_comment", db.String(20))
lock_id = db.Column("lock_id", db.BIGINT, primary_key=True)
def __init__(self, admin_id, key_id, key_comment, lock_id):
self.admin_id = admin_id
self.key_id = key_id
self.key_comment = key_comment
self.lock_id = lock_id
def __repr__(self):
return 'Administrator %r' % self.admin_id
运行总是报错:<(OperationalError) (1075, 'Incorrect table definition; there can be only one auto column and it must be defined as a key') '\nCREATE TABLE admin_info (\n\tadmin_id VARCHAR(20) NOT NULL, \n\tkey_id INTEGER NOT NULL, \n\tkey_comment VARCHAR(20), \n\tlock_id BIGINT NOT NULL AUTO_INCREMENT, \n\tPRIMARY KEY (admin_id, key_id, lock_id)\n)\n\n' ()> ps:恶心死我了
但是这么简单代码,我一行一行的检查,并没有发现什么错误啊。于是我就只有请出谷歌兄帮忙了,捣腾了大半天,我艹,终于找到问题出在哪儿了。。。原来在新建表的时候,添加多主键是由默认规则的,SQLAlchemy文档如是说:“When creating tables, SQLAlchemy will automatically set AUTO_INCREMENT on the first Integer primary key column which is not marked as a foreign key.You can disable this behavior by passing False to the autoincrement argument of Column. This flag can also be used to enable auto-increment on a secondary column in a multi-column key for some storage engines”,擦,这就是问题的关键了,我的key_id就是定义为整型的,且为主键,它给劳资默认为自增长的了,怪不得报错,尼玛,坑死我了。。。最后说一下解决办法吧,在key_id = db.Column("key_id", db.INT, primary_key=True)这行的括号里边添加一句autoincrement=False就OK了
发帖的初衷是希望以后用到SQLAlchemy进行多主建设置的时候不要再被坑了 |
|