SQLAlchemy on the way

SQLAlchemy Trial

This is a great ORM ( Object-Relational Mapper ) which is compatible with  xxxx and many others.

 

SQLAlchemy 0.8 Documentation

link: http://docs.sqlalchemy.org/en/rel_0_8/orm/examples.html

        

IMPORTANT TO GO THROUGH

Object Relational Tutorial

http://docs.sqlalchemy.org/en/rel_0_8/

  

 

 

需要看的东西:

python - __str__ 和 __repr__ 的区别!!

原帖地址:  http://blog.csdn.net/yyt8yyt8/article/details/7030416

内建函数str()和repr() (representation,表达,表示)或反引号操作符(``)可以方便地以字符串的方式获取对象的内容、类型、数值属性等信息。str()函数得到的字符串可读性好(故被print调用),而repr()函数得到的字符串通常可以用来重新获得该对象,通常情况下 obj==eval(repr(obj)) 这个等式是成立的。这两个函数接受一个对象作为其参数,返回适当的字符串。

事实上repr()和``做一样的事情,返回一个对象的“官方”字符串表示。其结果绝大多数情况下(不是所有)可以通过求值运算(内建函数eval())重新得到该对象。

str()则不同,它生成一个对象的可读性好的字符串表示,结果通常无法用eval()求值,但适合print输出。

如下例:

>>> class D(object):
...     def __str__(self):
...         return "a __str__"
...     def __repr__(self):
...         return "a __repr__"
...
>>> dr = D()
>>> print dr
a __str__
>>> dr
a __repr__
>>> "%s" % dr
'a __str__'
>>> "%r" % dr
'a __repr__'
>>> dr
a __repr__
>>>print dr
'a __str__'

 

为什么有了repr()还需要``? 

 Python中,有的操作符和函数是做同样的事情,原因是某些场合下函数会比操作符更适合使用,比如函数对象可作为参数传递。双星号(**)乘方运算和pow()内建函数都返回x的y次方.

其他专用类的方法:python_专用类方法 

链接地址:http://www.cnblogs.com/xupeizhi/archive/2012/07/20/2601598.html

 

 基本的code可以是这样的

# create SQL engine
from sqlalchemy import create_engine

# To maintain a catalog of classes and tables relative to that base
from sqlalchemy.ext.declarative import declarative_base

# To accomplish the class mapped to the table with objects that present \
# the components of our table
from sqlalchemy import Column, Integer, String


# To start a session to talk to SQL database
from sqlalchemy.orm import sessionmaker

# [Create Engine]
engine = create_engine('sqlite:///:memory:', echo = True)

# An instance to set rules :)
Base = declarative_base()

class  User(Base):
    __tablename__='users'

    id = Column(Integer, primary_key= True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password

    # Optional: This is used for to check out elments visually
    def __repr__(self):
        return "<User('%s', '%s', '%s')>" % (self.name, self.fullname, self.password)

# start a session class instance
Session = sessionmaker()

# Bind engine to a session
Session.configure(bind=engine)  # once engine is available

# instantiate a session
session = Session()

# The above Session is associated with our SQLite-enabled Engine,\
# but it hasn’t opened any connections yet. \
# When it’s first used, it retrieves a connection \
# from a pool of connections maintained by the Engine, 
# and holds onto it until we commit all changes and/or close the session object.

 

然后,根据提示下面继续。session的内容,session filter

 很重要的内容:

http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html#adding-new-objects

 

 

在session这里面,很有意思,当取出来数据的时候。比如

thief = session.query(User).filter_by(name="wendy").first()

 这时候,修改thief.name = "jake"

然后再session.commit()

会发现数据库里面数据被改动了。wendy变成jake了。

×××用等于号直接赋值,相当于是别名,都还是在同一个对象上进行操作的。

如果我们只是想取得数据的副本,而不是对原数据进行操作的话。

因为直接操作的都是class 对象,所以不能采用像是数组、元组、那样新建一个slice切片 a = b[:],这样在这种对象复制中是不行的。这里可以使用copy模块。

    import copy

  copy模块分为1浅拷贝(默认拷贝) 2深拷贝

    1.浅拷贝 只拷贝子类,不拷贝对象的父类

    2.深拷贝拷贝对象的子类与父类

---------------这样拷贝对象,进行操作后,也不会在session.commit() 后,对数据造成错误处理了。这样是为了方便既要修改数据又要只提取部分数据的工作。

详情请看 http://www.jb51.net/article/15714.htm Python

拷贝对象(深拷贝deepcopy与浅拷贝copy)

 

关于session,还有一些session.dirty的用法

We can add more User objects at once using add_all():

>>> session.add_all([
...     User('wendy', 'Wendy Williams', 'foobar'),
...     User('mary', 'Mary Contrary', 'xxg527'),
...     User('fred', 'Fred Flinstone', 'blah')])

Also, Ed has already decided his password isn’t too secure, so lets change it:

>>> ed_user.password = 'f8s7ccs'

The Session is paying attention. It knows, for example, that Ed Jones has been modified:

>>> session.dirty
IdentitySet([<User('ed','Ed Jones', 'f8s7ccs')>])

and that three new User objects are pending:

>>> session.new  
IdentitySet([<User('wendy','Wendy Williams', 'foobar')>,
<User('mary','Mary Contrary', 'xxg527')>,
<User('fred','Fred Flinstone', 'blah')>])

We tell the Session that we’d like to issue all remaining changes to the database and commit the transaction, which has been in progress throughout. We do this via commit():

sql>>> session.commit()

 

 

 

posted @ 2013-09-25 23:05  spaceship9  阅读(342)  评论(0编辑  收藏  举报