Python 经典问题:如何向表中插入数据:图书、作者、图书作者?
我想要3张桌子:Python 经典问题:如何向表中插入数据:图书、作者、图书作者?,python,sql,sqlalchemy,Python,Sql,Sqlalchemy,我想要3张桌子: 书籍(id、标题、自动递增(id)) 作者(id、姓名、自动递增(id)) 图书作者(图书id,作者id) 我希望在一个事务中完成所有操作,以确保只有在所有表中的所有操作都正常时,数据才会插入到表中 要将任何内容插入到book\u author中,我需要我没有的id 我应该: 将数据插入到books表中,进行选择以获取ID 将数据插入到author表中,进行选择以获取ID 将两个id插入book\u作者 ? 或者我应该在插入时使用触发器?但这是一种使触发器依赖于两个插入的方
- 书籍(id、标题、自动递增(id))
- 作者(id、姓名、自动递增(id))
- 图书作者(图书id,作者id)
book\u author
中,我需要我没有的id
我应该:
books
表中,进行选择以获取IDauthor
表中,进行选择以获取IDid
插入book\u作者
第二个问题也许这很重要。。。。如果某些数据库不支持自动增量,该怎么办?如果有大量记录保存到表中,则在使用SELECT语句创建记录后定位记录的ID可能会有问题。使用触发器可以轻松引用插入的最后一条记录。这是一个例子
触发器还将帮助您自动增加表的ID字段。你可以看到一个例子 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
这是什么背景?您使用的是Django还是其他类型的框架?@sean:我有很多用python编写的东西,可以从XML中提取数据并尝试插入数据库。为了更好地帮助您,最好知道您使用的是Django还是其他类型的数据库ORM。这样我们可以更好地帮助您解决上述问题。这就是交易的目的;您在所有插入完成后提交。@Martijn:我正在尝试使用sqlalchemy。但我是否应该选择询问数据库关于ID的信息,哪个数据库给出了特定的记录?