SQLAlchemy (一)---创建表、插入数据、查询

本文介绍了使用SQLAlchemy库在Python中创建数据库表格、插入数据及进行单表和多表查询的基本步骤。通过示例代码展示了如何创建user和address表,以及如何向这些表中插入数据。同时,详细讲解了如何执行单表查询和涉及两个表的联合查询,帮助读者理解SQLAlchemy的实用功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、创建数据库表格

建立Python文件alchemy5.py,代码如下:

#!/usr/bin/ python
#encoding:utf8

from sqlalchemy import *
from sqlalchemy.orm import *
#from sqlalchemy.ext.declarative import declarative_base

#功能:创建数据库表格,初始化数据库

#定义引擎
engine = create_engine('mysql+mysqlconnector://root:111111@localhost:3306/testalchemy')
#绑定元信息
metadata = MetaData(engine)

#创建表格,初始化数据库
user = Table('user', metadata,
    Column('id', Integer, primary_key = True),
    Column('name', String(20)),
    Column('fullname', String(40)))
address = Table('address', metadata, 
    Column('id', Integer, primary_key = True),
    Column('user_id', None, ForeignKey('user.id')), 
    Column('email', String(60), nullable = False),
)
#创建数据表,如果数据表存在则忽视!!!
metadata.create_all(engine)
#获取数据库链接,以备后面使用!!!!!
conn = engine.connect()

结果如图:
这里写图片描述

二、插入数据

建立Python文件alchemy6.py,代码如下:

#!/usr/bin/ python
#encoding:utf8

from sqlalchemy import *
from sqlalchemy.orm import *
#alchemy5实现创建数据库表格功能
from alchemy5 import *
#############一.以每次插入一条记录的方式向user表插入数据##############
#使用查询
i = user.insert()
#print i
#插入一组数据
u = dict(name='tom', fullname='tom smith')#id从1自动增加
#执行查询,第一个为查询对象,第二个参数为一个插入数据字典,如果插入的是多个对象
#就把对象字典放在列表里边
r1 = conn.execute(i, **u)
#print r1
#返回插入行
print r1.inserted_primary_key
############二.以每次插入多条记录的方式向address表插入数据#############
addr = [{'user_id': 1, 'email': 'jack@yahoo.com'}, {'user_id': 1,
'email': 'jack@msn.com'}, {'user_id': 2, 'email': 'www@www.org'}, 
{'user_id': 2, 'email': 'wendy@aol.com'}]
j = address.insert()
r2 = conn.execute(j, addr)

结果如图:

1、user表(插入数据更改过名字)
这里写图片描述

2、address表
这里写图片描述

三、查询

1、单个表的查询
建立Python文件alchemy7.py,代码如下:

#!/usr/bin/ python
#encoding:utf8

from sqlalchemy import *
from sqlalchemy.orm import *
#alchemy5实现创建数据库表格功能
from alchemy5 import *
#alchemy6实现插入数据
#from alchemy6 import *

#功能:实现单个表的查询

print '#'*15
s1 = select([user])  #查询全表
print s1
r1 = conn.execute(s1) #执行查询

print r1.fetchall() #返回查询结果!!!!!
# 只要 r.fetchall() 之后,就会自动关闭 ResultProxy 对象
print '#'*15
#user.c表 user 的字段column对象
s2 = select([user.c.name, user.c.fullname]) #查询部分
print s2
r2 = conn.execute(s2) #执行查询

#r1.fetchall() #返回查询结果!!!!!

print '#'*15

结果:
这里写图片描述

2、两个表的查询

建立Python文件alchemy8.py,代码如下:

#!/usr/bin/ python
#encoding:utf8

from sqlalchemy import *
from sqlalchemy.orm import *
#alchemy5实现创建数据库表格功能
from alchemy5 import *

#功能:实现同时对两个表的查询

print '#'*15
s = select([user.c.name, address.c.user_id]).where(user.c.id == address.c.user_id)
print s
r = conn.execute(s) #执行查询
result = r.fetchall() #返回查询结果!!!!!
print result
print '#'*15

结果:
这里写图片描述

The SQLAlchemy Object Relational Mapper presents a method of associating user-defined Python classes with database tables, and instances of those classes (objects) with rows in their corresponding tables. It includes a sys- tem that transparently synchronizes all changes in state between objects and their related rows, called a unit of work, as well as a system for expressing database queries in terms of the user defined classes and their defined relationships between each other. The ORM is in contrast to the SQLAlchemy Expression Language, upon which the ORM is constructed. Whereas the SQL Expression Language, introduced in SQL Expression Language Tutorial, presents a system of representing the primitive constructs of the relational database directly without opinion, the ORM presents a high level and abstracted pattern of usage, which itself is an example of applied usage of the Expression Language. While there is overlap among the usage patterns of the ORM and the Expression Language, the similarities are more superficial than they may at first appear. One approaches the structure and content of data from the perspective of a user-defined domain model which is transparently persisted and refreshed from its underlying storage model. The other approaches it from the perspective of literal schema and SQL expression representations which are explicitly composed into messages consumed individually by the database. A successful application may be constructed using the Object Relational Mapper exclusively. In advanced situations, an application constructed with the ORM may make occasional usage of the Expression Language directly in certain areas where specific database interactions are required. The following tutorial is in doctest format, meaning each >>> line represents something you can type at a Python command prompt, and the following text represents the expected return value.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值