SQLAlchemy最新权威详细教程 前言:最近开始学习SQLAlchemy,本教程是其官方文档以及在读英文版的翻译加一些自己的理解和总结 1 什么是 SQLAlchemy? 它是给mysql, oracle,sqlite等关系型数据库的python接口,不需要大幅修改原有的python代码,它已经包含了SQL表达式语言和ORM,看一些例子: sql=”INSERT INTO user(user_name, password) VALUES (%s, %s)” cursor = conn.cursor() cursor.execute(sql, (‘dongwm’, ‘testpass’)) 以上是一个常用的mysql的SQL语句,但是冗长也容易出错,并且可能导致安全问题(因为是字符串的语句,会存在SQL注入),并且代码不跨平台,在不同数据库软件的语句不同(以下是一个 Oracle 例子),不具备客移植性: sql=”INSERT INTO user(user_name, password) VALUES (:1, :2)” cursor = conn.cursor() cursor.execute(sql, ‘dongwm’, ‘testpass’) 而在SQLAlchemy里只需要这样写: statement = user_table.insert(user_name=’rick’, password=’parrot’) statement.execute() #护略是什么数据库环境 SQLAlchemy还能让你写出很 pythonic的语句: statement = user_table.select(and_( user_table.c.created >= date(2007,1,1), user_table.c.created < date(2008,1,1)) result = statement.execute() #检索所有在2007年创建的用户 metadata=MetaData(‘sqlite://’) # 告诉它你设置的数据库类型是基于内存的sqlite user_table = Table( #创建一个表 ‘tf_user’, metadata, Column(‘id’, Integer, primary_key=True), #一些字段,假设你懂 SQL,那么以下的字段很好理解 Column(‘user_name’, Unicode(16), unique=True, nullable=False), Column(‘email_address’, Unicode(255), unique=True, nullable=False), Column(‘password’, Unicode(40), nullable=False), Column(‘first_name’, Unicode(255), default=”), Column(‘last_name’, Unicode(255), default=”), Column(‘created’, DateTime, default=datetime.now)) users_table = Table(‘users’, metadata, autoload=True) #假设 table 已经存在.就不需要指定字段,只是加个 autoload=True class User(object): pass #虽然 SQLAlchemy强大,但是插入更新还是需要手动指定,可以使用 ORM,方法就是:设定一个类,定义一个表...