Python ORM框架SQLAlchemy学习笔记之安装和简单查询实例
最近正好在寻求一种Python的数据库ORM (Object Relational Mapper),SQLAlchemy (项目主页)这个开源项目进入了我的视线,本来想尝试着使用Django的ORM模块的,无奈Django的模块联系比较紧密,没能单独分拆下来,一定程度上说明Django自成体系的生态系统在给我们带来快速便捷的开发环境的同时牺牲了组装的灵活性。
初次学习,也没实质感觉到SQLAlchemy的好处,不过看其介绍的很多大公司均采用该项目,而且其支持的数据库还是蛮丰富的,所以我觉得花点时间研究还是值得的。不过令人遗憾的是关于SQLAlchemy的中文资料比较少,所以对于我们这种英语不佳的带来了一定的麻烦。
研究一个项目最好的办法就是阅读其官方提供的说明文档,当然很轻松就找到了SQLAlchemy的文档 (0.7)。文档的格式和大多数项目一样,有下载安装说明,有示例,有快速上手教程。不过我还是习惯下载个PDF慢慢研究。
下面就将我近期的阅读学习做个笔记,当然这个仅供参考,里面可能有自己的一些猜测和想法,不作权威依据,不当之处还希望指出。
1. 安装SQLAlchemy
安装部分不打算详细介绍,可以通过easy_install或者pip进行安装,命令如下:
代码如下:
easy_install SQLAlchemy
# 或者
pip install SQLAlchemy
当然我使用的是Windows环境,所以倾向于使用setup.py安装,下载压缩包,解压,然后命令提示符下切换到该目录,再运行下面的命令:
代码如下:
python setup.py install
这里需要注意的是默认安装会编译安装C扩展,这些C扩展将直接编译为二进制本机代码然后为SQLAlchemy处理数据集加速,这个是很不错的功能,遗憾的是Windows下提示编译安装扩展失败,当然这不影响SQLAlchemy的使用,只是作为性能上的优化,本机开发环境可以不需要这些扩展,如果不需要可以尝试下面的命令:
代码如下:
pip install --global-option='--without-cextensions' SQLAlchemy
# 或者setup.py方式
python setup.py --without-cextensions install
好了,到这里安装部分我就简单介绍完了,如果对这部分感兴趣的话可以移步文档。
最后可以检验一下安装成果:
代码如下:
>>> import sqlalchemy
>>> sqlalchemy.__version__
0.7.0
2. 简单的查询
就像任何新语言都是从万能的'Hello World'开始一样,先简单体验一把SQLAlchemy,由于SQLAlchemy是管理数据库的,所以我们需要一个数据库,自从用了Python以后,一提到数据库,拿来做实验的首当其冲的就是Python自带的SQLite3,这次我们连SQLite的数据库文件都不需要指定了,直接创建一份基于内存的数据库,也就是说数据文件存放在内存中,便于我们下面的测试。
我们使用create_engine创建数据库连接引擎:
代码如下:
>>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///:memory:', echo=True)
create_engine的第一个参数'sqlite:///:memory:'我们知道是建立数据库连接的,那第二个参数echo=True是做什么的呢,其实如果echo=True那么SQLAlchemy将会通过Python标准模块logging来输出日志,如果你在操作交互式命令控制台,一些信息将会被输出,这里我们可能会看到SQLAlchemy生成的一些SQL语句,这个对于我们学习和调试是很有必要的,所以在这里我们将其设置为True,否则,如果不愿意SQLAlchemy这么啰嗦的话可以设置为False,这样就看不到这些信息啦。
create_engine()将会返回一个Engine引擎实例(instance),其代表着SQLAlchemy对于数据库的核心接口,其隐藏了各种数据库方言(dialect)的细节,实际上SQLAlchemy的底层是Python的DBAPI。
需要注意的是此时并没有实质上与数据库建立连接,什么时候才会与数据库真正建立连接呢?这个只会在你第一次查询数据库的时候发生。呃…这个有点像Lazy Loading (懒惰加载,延迟加载),也就是说我们需要真正操作数据库的时候才真正建立连接。SQLAlchemy很多地方用到了Lazyload,以后会有机会和大家介绍的。
接下来我们来执行第一条SQL语句,同时建立数据库连接:
代码如下:
>>> engine.execute("select 1").scalar()
1
好了,当engine.execute执行时,Engine终于建立起实质上数据库连接了。
Engine对于数据库连接的管理采取的是数据库连接池 (Pool),当连接第一次建立,SQLAlchemy将会将建立的连接放入内部的连接池中以便于随后的数据操作语句执行时复用。
当然关于Engine的用法并不是SQLAlchemy精彩的ORM部分,随后我们会介绍将Engine绑定到ORM,然后使用对象来操作数据库部分。

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.
