web2py 插入方法
Web2py 文档有两种插入数据库的方法
db.tbl[0] = newRow
,
db.tbl.insert(newRowAsDict)
文档暗示它们是同义词,但它们似乎不同。其一,如果 newRow 包含表中不存在的字段,则 insert 方法会引发异常。此外,.insert 方法返回所添加行的 id,而赋值则不会返回。
- 这是预期的行为吗?
- 如果我使用赋值方法,如何获取 id?
- 赋值方法是否被废弃?
Web2py docs have two methods for inserting into a database
db.tbl[0] = newRow
and
db.tbl.insert(newRowAsDict)
The documentation implies that they are synonyms, but they appear to be different. For one, the insert method throws an exception if newRow contains fields that are not in the table. Also the .insert method returns the id of the added row, where the assignment doesn't.
- Is this the intended behavior
- How can I get the id if I use the assignment method?
- Is the assignment method depricated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
一点点的探索显示了两者之间的区别:
对于:db.tbl[0] = dict(name='something')
File "/var/web2py/gluon/globals.py", line 172, in <lambda>
self._caller = lambda f: f()
File "/var/web2py/applications/myapp/controllers/default.py", line 114, in test
db.tbl[0] = dict(name='something')
File "/var/web2py/gluon/dal.py", line 5531, in __setitem__
self.insert(**self._filter_fields(value))
File "/var/web2py/gluon/dal.py", line 5605, in insert
return self._db._adapter.insert(self,self._listify(fields))
对于:db.tbl.insert(name=') some')
File "/var/web2py/gluon/globals.py", line 172, in <lambda>
self._caller = lambda f: f()
File "/var/web2py/applications/myapp/controllers/default.py", line 115, in test
db.tbl.insert(name='something')
File "/var/web2py/gluon/dal.py", line 5605, in insert
return self._db._adapter.insert(self,self._listify(fields))
它们最终都会调用相同的代码来执行插入,因此您会看到它们运行相同的查询:
INSERT INTO tbl(name) VALUES ('something');
因为前者执行 _filter_fields
从跟踪中可以明显看出,当存在时它不会抛出异常是表中不存在的字段,而另一个是表中存在的字段。
显然,db.tbl[0] = newRow
无法返回值。您应该将其视为 insert 的简写,其表亲 db.tbl[x>0]
对于更新非常有用,并且具有完全相同的表示法,这有助于简化代码。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
还有
一个会过滤 newRowAsDict 中的键,忽略未知字段。
There is also
which will filter the keys in newRowAsDict ignoring unknown fields.