1. 创建映射类的实例(Instance)
前面介绍了如何将数据库实体表映射到Python类上,下面我们可以创建这个类的一个实例(Instance),我们还是以前一篇文章的User类为例,让我们创建User对象:
>>> ed_user = User('ed', 'Ed Jones', 'edspassword')
>>> ed_user.name
'ed'
>>> ed_user.password
'edspassword'
>>> str(ed_user.id)
'None'
和普通的Python类一样实例化,大家可能会问为什么ed_user.id会是None值,首先id这个属性没有通过__init__()构造方法初始化,所以默认会因为先前定义的ORM的id列(Column)而产生一个None值,在默认情况下,ORM会为所有被映射的表列创建类属性,这些属性是通过Python语言中描述符(Descriptors)机制来实现的。所以这些属性的使用会包含一些额外的行为,包括跟踪修改,或者当需要时自动从数据库加载新的数据,也就是说我们在使用这些属性时,包括修改或者读取,都会触发ORM内部的一系列动作。
等等,你还没有说明白为什么id这个属性会为None值呢。呵呵,其实我们现在并没有将数据插入数据库,一般主键这个属性会在插入数据库时自动产生一个不重复的值以保证唯一性。由于我们没有对对象实行持久化(Persist) (所谓的持久化就是把对象数据按照映射关系存储入数据库里) 所以这里id值为None。别着急,稍后当我们介绍将数据持久化后你就可以看到一个新的自动产生的id了。
接下来小偷懒一下,介绍一个偷懒的技巧:-)
假如我们不定义映射类的构造方法__init__()会带来什么不良影响吗?完全不会,SQLAlchemy为我们考虑到这点,假如我们偷懒将先前的User类定义成这样:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
由于User继承自Base (Base定义见上一篇文章),所以受到Declarative系统的管理,Declarative系统发现这个类缺少构造方法,于是很友善的给我们补上了一个构造方法,当然其提供的构造方法则不能像我们自己定义的构造方法那样使用基于位置的参数访问,建议使用基于键的参数访问方式,包括我们所有用Column定义映射的列,比如如下方式:
u1 = User(name='ed', fullname='Ed Jones', password='foobar')
id也可以传入,通常意义上这类主键由系统自动维护,我们无需为其赋值。
2. 创建并使用会话(Session)
到这里可谓是“万事俱备,只欠东风了”,用官方文档的话说“我们现在已经准备好和数据库‘交谈'了” (We're now ready to start talking to the database)。ORM的操作句柄(Handle)被称为会话(Session)。为了使用会话,我们需要先配置它,配置Session的代码语句应该和create_engine()创建引擎的代码语句在一个代码级别上(放在一起就行了)。
比如我们利用create_engine()先建立起引擎名字为engine(关于引擎的建立代码可以参考我第一篇文章),然后利用sessionmaker()工厂函数建立起Session类,同时绑定我们现有的引擎,比如代码如下:
>>> from sqlalchemy.orm import sessionmaker
>>> Session = sessionmaker(bind=engine)
假如我们创建Session的代码与创建引擎的代码不在一个级别上呢,比如先sessionmaker()一个Session类,然后才用create_engine()创建了引擎,那么我们还有机会将Session和引擎绑定到一起吗?当然可以,我们可以利用Session类的configure方法来配置引擎绑定,比如这样的:
Session = sessionmaker()
# engine = create_engine(...) 创建引擎
Session.configure(bind=engine) # 到这里engine应该已经创建
到这里通过sessionmaker()工厂创造出的Session类应该绑定了我们先前创建的Engine了,但是会话还没有真正开始,要开始会话我们需要实例化这个Session类:
>>> session = Session()
到这里session就获取了由Engine维护的数据库连接池,并且会维持内存中的映射数据直到提交(commit)更改或者关闭会话对象。
到这里会话的建立就讲解完了,接下来会讲解真正的ORM数据库查询部分,欢迎关注!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.