zoukankan      html  css  js  c++  java
  • python---ORM之SQLAlchemy(5)联合唯一的使用

    # coding:utf8
    # __author:  Administrator
    # date:      2018/3/16 0016
    # /usr/bin/env python
    import sqlalchemy
    from sqlalchemy import create_engine
    from sqlalchemy import String,Column,Integer,ForeignKey,UniqueConstraint
    from sqlalchemy.orm import relationship,sessionmaker
    from sqlalchemy.ext.declarative import declarative_base
    
    engine = create_engine("mysql+pymysql://root:root@127.0.0.1/t2")
    
    Base = declarative_base()
    
    class Test(Base):
        __tablename__ = 'test'
        id = Column(Integer,primary_key=True)
        name = Column(String(40))
        age = Column(Integer)
    
      #在__table_args__中设置索引,为元组 __table_args__
    = ( UniqueConstraint('name','age'),#姓名和年龄唯一
    )

    Base.metadata.create_all(engine)

    MySession
    = sessionmaker(bind=engine)

    session
    = MySession()

    t1
    = Test(name='asd',age=11)
    t2
    = Test(name='asd',age=12)

    session.add_all([t1,t2])

    session.commit()

    上面是可以成功的,但是当你想再添加一个,name,age相同的数据是,会报错

    t3 = Test(name='asd',age=11)
    
    session.add(t3)
    session.commit()
    #sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (
    1062, "Duplicate entry 'asd-11' for key 'name'") [SQL: 'INSERT INTO test (name, age) VALUES (%(name)s, %(age)s)'] [parameters: {'name': 'asd', 'age': 11}] (Background on this error at: http://sqlalche.me/e/gkpj)
  • 相关阅读:
    Centos7新特性——systemd取代init管理服务
    Git初探
    Nginx内置变量
    Nginx初探
    PHP多进程初步
    golang消息队列nsq
    golang 的 go异步编程通道要注意的问题
    golang 连接池mysql
    golang centos运行方法
    golang go path和go mod的区别
  • 原文地址:https://www.cnblogs.com/ssyfj/p/8582234.html
Copyright © 2011-2022 走看看