0

我想要3张桌子:

  • 书籍(id,标题,自动增量(id))
  • 作者(id,名称,自动增量(id))
  • book_author(book_id, author_id)

我想在一个事务中完成所有事情,以确保只有在所有表中一切正常时,数据才会插入到表中。

要插入任何东西,book_author我需要我没有的 id。

我是不是该:

  1. 向表中插入数据books,进行选择以获取 ID,
  2. 向表中插入数据author,进行选择以获取 ID,
  3. 插入id两个book_author

?

或者也许我应该在插入时使用触发器?但它是一种使触发器依赖于两个插入的方法吗?

我会有所帮助,我可以说我正在尝试使用 python 和 sqlalchemy。


第二个问题也许这很重要....如果某些数据库不支持自动增量怎么办?

4

2 回答 2

2

SQLAlchemy 对象关系 API 为您完成所有工作:添加记录、事务支持、自动递增列值。因此,您无需为每个对象保存 id 并为每个关系创建记录。用示例展示这一点的最佳方式:

from sqlalchemy import *
from sqlalchemy import create_engine, orm
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

__author__ = 'vvlad'

metadata = MetaData()
Base = declarative_base()
Base.metadata = metadata


"""many-to-many relationship table"""
author_book = Table(
    'author_book', Base.metadata,
    Column('author_id',String(11),ForeignKey('author.id')),
    Column('book_id',Integer,ForeignKey('book.id')),
)

class Author(Base):
    __tablename__ = 'author'
    """SQLAlchemy's Sequence(name) for Column allows to have database agnostic autoincrement"""
    id = Column(Integer, Sequence('author_seq'), primary_key=True)
    name = Column(String(length=255))
    def __repr__(self):
        return "%s(name=\"%s\",id=\"%s\")" % (self.__class__.__name__,self.name,self.id)


class Book(Base):
    __tablename__ = 'book'

    id = Column(Integer, Sequence('book_seq'),primary_key=True)
    name = Column(String(length=255))
    """Defines many-to-many relations"""
    authors = relationship(Author,secondary=author_book,backref="books",collection_class=list)


    def __repr__(self):
        return "%s(name=\"%s\",id=\"%s\")" % (self.__class__.__name__,self.name,self.id)




db = create_engine('sqlite:////temp/test_books.db',echo=True)

#making sure we are working with a fresh database
metadata.drop_all(db)
metadata.create_all(db)

sm = orm.sessionmaker(bind=db, autoflush=True, autocommit=True, expire_on_commit=True)
session = orm.scoped_session(sm)

"""associating authors with book"""
b1 = Book(name="Essential SQLAlchemy")
a1 = Author(name="Rick Copeland")
"""associating book with author"""
a1.books.append(b1)
b2 = Book(name="The Difference Engine")
gibson = Author(name="William Gibson")
b2.authors.append(gibson)
b2.authors.append(Author(name="Bruce Sterling"))

b3 = Book(name="Pattern Recognition")
b3.authors.append(gibson)
try:
    #here your transaction start
    #adding objects to session. SQLAlchemy will add all related objects into session too
    session.add(b2)
    session.add(a1)

    session.add(b3)
    #closing transaction
    session.commit()
#remember to put specific exceptions instead of broad exception clause
except:
    """if something went wrong - rolls back session (transaction)"""
    session.rollback()

print "Book info"
b3 = session.query(Book).filter(Book.name=="Essential SQLAlchemy").one()
print b3
for author in b3.authors:
    print author


aname = "William Gibson"
print "Books of author %s" % aname
for book in session.query(Book).join(author_book).join(Author).filter(Author.name==aname).all():
    print book
    for author in book.authors:
        print author
于 2013-01-16T16:53:10.027 回答
0

如果您有大量记录保存到表中,则在使用 SELECT 语句创建记录后查找记录的 ID 可能会出现问题。使用触发器将允许您轻松引用最后插入的记录。这是一个教程

触发器还将帮助您自动增加表的 ID 字段。你可以在这里看到一个例子。

于 2013-01-16T03:47:58.620 回答