sqlalchemy:如何在mysql中添加带auto_increment的表行

时间:2013-06-12 19:57:43

标签: mysql sqlalchemy

我正在使用sqlalchemy 0.8和mysql 5.5

我有一个简单的表,其ORM定义如下所示

class TrackingTable(db.Model):

    __tablename__ = 'tracking_table'

    trackid = db.Column(db.BigInteger,primary_key=True)
    custid = db.Column(db.String(20), db.ForeignKey('customer.id'))
    tracktime = db.Column(db.DateTime ,nullable=False)
    formdata = db.Column(db.String(100),nullable=False)

我假设(根据文档)trackid是BIGINT类型的主键,因此它将自动递增。

但是当我尝试在db

中添加记录时
updateRecord = TrackingTable(custid='002',tracktime='2013-02-02',formdata='logged in')

db_session.add(updateRecord)
db_session.flush()
db_session.commit()

它发出警告 警告:字段'trackid'没有默认值

对于trackid,它总是取0的值,因此第二次添加总是失败并出错 IntegrityError:(IntegrityError)(1062,“重复输入'0'用于键'PRIMARY'”)'INSERT INTO tracking_table(custid,tracktime,formdata)

Pl帮助我解决这个问题。理想情况下,我希望这是一个由数据库处理的递增值,但我无法弄清楚如何实现这一点。

提前致谢

2 个答案:

答案 0 :(得分:0)

您需要将字段值设置为“AUTO_INCREMENT”,而不是将实际值传递给它传递NULL。尝试首先传递NULL,因为它可能已经设置为AUTO_INCREMENT。

答案 1 :(得分:0)

无法重现,在这里工作正常:

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class TrackingTable(Base):

    __tablename__ = 'tracking_table'

    trackid = Column(BigInteger, primary_key=True)
    formdata = Column(String(100), nullable=False)

e = create_engine("mysql://scott:tiger@localhost/test", echo=True)
Base.metadata.create_all(e)

s = Session(e)

updateRecord = TrackingTable(formdata='logged in')

s.add(updateRecord)
s.commit()

print updateRecord.trackid

输出(记录垃圾修剪):

SELECT DATABASE()
SHOW VARIABLES LIKE 'character_set%%'
SHOW VARIABLES LIKE 'sql_mode'
DESCRIBE `tracking_table`
ROLLBACK

CREATE TABLE tracking_table (
trackid BIGINT NOT NULL AUTO_INCREMENT, 
formdata VARCHAR(100) NOT NULL, 
PRIMARY KEY (trackid)
)

COMMIT
BEGIN (implicit)
INSERT INTO tracking_table (formdata) VALUES (%s)
('logged in',)
COMMIT
BEGIN (implicit)
SELECT tracking_table.trackid AS tracking_table_trackid, tracking_table.formdata AS tracking_table_formdata 
FROM tracking_table 
WHERE tracking_table.trackid = %s
(1L,)
1