码迷,mamicode.com
首页 > 数据库 > 详细

web.py数据库操作方法指南 -《狗嗨默示录》-

时间:2017-08-13 12:18:10      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:esc   pos   fse   date   com   条件   query   statement   ble   

1. 导入模块,定义数据库连接db

import web
db = web.database(dbn=postgres,  user=dbuser, pw=‘‘, db=mydata)

2. select 查询

# 查询表
entries = db.select(mytable)

# where 条件
myvar = dict(name="Bob")
results = db.select(mytable, myvar, where="name = $name")
results = db.select(mytable, where="id>100")
# 查询具体列
results = db.select(mytable, what="id,name")

# order by
results = db.select(mytable, order="post_date DESC")

# group
results = db.select(mytable, group="color")

# limit
results = db.select(mytable, limit=10)

# offset
results = db.select(mytable, offset=10)

3. 更新

db.update(mytable, where="id = 10", value1 = "foo")

4. 删除

db.delete(mytable, where="id=10")

5. 复杂查询

# count
results = db.query("SELECT COUNT(*) AS total_users FROM users")
print results[0].total_users

# join
results = db.query("SELECT * FROM entries JOIN users WHERE entries.author_id = users.id")

# 防止SQL注入可以这么干
results = db.query("SELECT * FROM users WHERE id=$id", vars={id:10})

6 多数据库操作 (web.py大于0.3)

db1 = web.database(dbn=mysql, db=dbname1, user=foo)
db2 = web.database(dbn=mysql, db=dbname2, user=foo)

print db1.select(foo, where=id=1)
print db2.select(bar, where=id=

7. 事务

t = db.transaction()
try:
    db.insert(person, name=foo)
    db.insert(person, name=bar)
except:
    t.rollback()
    raise
else:
    t.commit()

# Python 2.5+ 可以用with
from __future__ import with_statement
with db.transaction():
    db.insert(person, name=foo)
    db.insert(person, name=bar)

web.py数据库操作方法指南 -《狗嗨默示录》-

标签:esc   pos   fse   date   com   条件   query   statement   ble   

原文地址:http://www.cnblogs.com/LiGoHi/p/7352633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!