SQLAlchemy 使用

本文介绍如何使用SQLAlchemy ORM进行数据库操作,包括安装配置过程及示例代码,演示了如何定义模型类并执行增删改查等基本操作。

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

因为有用到 所以记录一下 呵呵

使用SQLAlchemy 这种ORM的方式操作数据库 

关于ORM的介绍具体可以参见 http://en.wikipedia.org/wiki/Object-relational_mapping

SQLAlchemy 官网:http://www.sqlalchemy.org/

安装方式:从源码包安装或者 easy_install SQLAlchemy(不得不说 用包安装真是方便啊 不用自己去安装各种依赖包)

安装mysql ap i: apt-get install python-mysqldb

 

使用的一个demo 

 1 #!/usr/bin/env python
 2 from   sqlalchemy import *
 3 from sqlalchemy import create_engine
 4 from sqlalchemy.ext.declarative import declarative_base
 5 from sqlalchemy import Column, Integer, String, ForeignKey
 6 from sqlalchemy import distinct
 7 from sqlalchemy.orm import sessionmaker
 8 #engine = create_engine('mysql://root:nosql@localhost/serverlist', echo=False)
 9 
10 engine = create_engine('mysql://users:passwd@localhost/videoupload', connect_args={'charset':'utf8'},echo=False)
11 Base = declarative_base()
12 Session = sessionmaker(bind=engine)
13 session = Session()
14 
15 class VideoUpload(Base):
16     __tablename__ = 'videoupload'
17     num      = Column(Integer, primary_key=True)
18     vid      = Column(String)
19     filepath = Column(String)    
20     sourceip = Column(String)
21     state    = Column(String)
22     snapshot = Column(String)
23     
24     
25     def __init__(self,vid='',filepath='',sourceip='',state='',snapshot=''):
26         self.vid      = vid
27         self.filepath = filepath
28         self.sourceip = sourceip
29         self.state    = state 
30         self.snapshot = snapshot
31 
32 
33 class FailVideoUpload(Base):
34     __tablename__ = 'fail_videoupload'
35     num               = Column(Integer, primary_key=True)
36     file_path         = Column(String)
37     file_name         = Column(String)
38     file_content_type = Column(String)
39     file_size         = Column(String)
40 
41     def __init__(self,file_path='',file_name='',file_content_type='',file_size=''):
42         self.file_path          = file_path
43         self.file_name          = file_name
44         self.file_content_type  = file_content_type
45         self.file_size          = file_size 
46      
47         
48         
49 if __name__ == '__main__':
50     #pVideoupload = VideoUpload()
51     #pVideoupload.insert().values(vid='123',sourceip='123',state='true',)
52     my_vp = VideoUpload('test', 'true', 'true','sdf')
53     my_fvp = FailVideoUpload('/home','123','jpg','123')
54     session.add(my_vp)
55     session.add(my_fvp)
56     session.commit()

 

转载于:https://www.cnblogs.com/jinjin666/archive/2013/01/28/2879546.html

SQLAlchemy是一个强大的Python ORM (Object-Relational Mapping) 库,它允许开发者以面向对象的方式来操作数据库。以下是使用SQLAlchemy的基本步骤: 1. **安装**: 首先需要通过pip安装SQLAlchemy库: ```bash pip install sqlalchemy ``` 2. **导入模块**: 导入sqlalchemy核心组件和你需要的具体数据库驱动,例如对于SQLite: ```python from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base ``` 3. **创建引擎**: 根据你的数据库配置创建数据库引擎,例如连接SQLite文件: ```python engine = create_engine('sqlite:///example.db') ``` 4. **定义模型** (Declarative Base): SQLAlchemy使用Declarative Base来简化表结构定义,它是元类,用于生成对应数据库表的类。 ```python Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) ``` 5. **映射数据到表**: 使用`Base.metadata.create_all(engine)`将定义的模型映射到数据库表上(如果表不存在的话)。 6. **查询数据**: 可以直接使用类名作为查询对象,例如获取所有用户: ```python users = User.query.all() ``` 7. **添加、更新和删除数据**: 对于增删改查操作,可以使用实例化对象并调用其对应的保存方法: ```python new_user = User(name='Alice') new_user.save() # 对应于INSERT INTO user = User.query.get(1) user.name = 'Bob' user.update() # 对应于UPDATE user.delete() # 对应于DELETE FROM ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值