aicode/kdb/sqlor.md
2026-01-29 16:05:25 +08:00

70 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 使用sqlor模块操作数据库
日期数据,在数据库中用date类型,日期格式:YYYY-MM-DD
时间戳数据,在数据库中用timestamp类型,格式:YYYY-MM-DD hh:mm:ss.999
sor.R()
sor.sqlExe() 的select语句
如果ns中有'page'属性,返回数据格式如下
{
"total" # 查询结果总记录数
"rows": page指定的页数据, 缺省每页返回80条记录,pagerows属性可设置每页记录数
}
否则返回全部记录的数组
```
from sqlor.dbpools import DBPools
from ahserver.serverenv import ServerEnv
# 假设当前模块名称为"mymodule"
async def subcoro(sor, pid):
sql = "select * from appcoodes_kw where parentid=${pid}$"
r = await sor.sqlExe(sql, {'pid': pid})
return r
async def sqlor_op():
db = DBPools()
env = ServerEnv()
dbname = env.get_module_dbname()
async with db.sqlorContext(dbname) as sor:
# 事务中,如果代码或sql失败全部滚回,正常结束自动提交
id = env.uuid()
# 执行SQL返回记录数组
sql="select * from user where name = ${name}$ and gender = ${gender}$"
ns = {'name': 'Make', 'gender': '0'}
recs = await sor.sqlExe(sql, ns)
## recs为[]或返回的记录数组
# 执行SQL返回分页数据
sql="select * from user where name = ${name}$ and gender = ${gender}$"
ns = {'name': 'Make', 'gender': '0', 'page': 2}
recs = await sor.sqlExe(sql, ns)
## recs是一个DictObject对象实例,转字典为:{
"total": 12222,
"rows": [ ... ]
}
# 执行其他DML,DDL语句
sql = "update user set gender=${gender}$ where name=${name}$"
ns = {'name': 'Make', 'gender': '0', 'page': 2}
ret = await sor.sqlExe(sql, ns)
## 返回修改记录数
# CRUD,对单表操作的简单方式
# 添加数据
await sor.C('user', {'id':id, 'username':'john'})
## 添加数据表“user”数据
# 删除数据,只从ns中提取id字段,根据id删除记录
await sor.D('user', {'id': 'yuewfiuwe'})
# 修改数据,ns中的id保存不变,其他给定的值为数据修改后的值
# await sor.U('user', {'id', 'email':'test@abc.com'})
# 查询数据,返回满足ns条件的全部记录数组
# await sor.R('user', {'id': 'yuewfiuwe'})
# 查询数据, 返回满足条件的参数“page”页的数据
ns={'gender':'1', 'page': 3, 'pagerows': 100} # pagerows 缺省80
return await subcoro(sor, 'test_data')
```