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
created >= date(2007,1,1), user_table
created < date(2008,1,1))