替换所有游标行中的值 [英] Replacing value in all cursor rows
问题描述
使用 SQLite 和 Python 3.1,我想通过在 HTML 表中显示货币数据.接受游标作为参数的模板.因此,所有货币值都必须有 2 个小数位,但 SQLite 将它们存储为浮点类型(即使结构声明十进制 :-( ),因此某些必须在显示前进行转换(例如,我希望 12.1 显示为 12.10).
Using SQLite and Python 3.1, I want to display currency data in a HTML table via. a template which accepts a cursor as a parameter. Hence all currency values must have 2 decimal places, but SQLite stores them as float type (even though the structure states decimal :-( ) so some must be converted before display (eg. I want 12.1 displayed as 12.10).
代码是这样的(为了说明而简化)...
The code goes something like this (simplified for illustration)...
import sqlite3
con = sqlite3.connect("mydb")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select order_no, amount from orders where cust_id=123")
for row in cur:
row['amount'] = format(row['amount'],'%.2f')
最后一条命令抛出错误#builtins.TypeError: 'sqlite3.Row' object does not support item assignment"
The last command throws the error "# builtins.TypeError: 'sqlite3.Row' object does not support item assignment"
如何解决无法更改行对象值的问题?我可以将光标转换为字典列表(每行一个,例如 [{'order_no':1, 'amount':12.1}, {'order_no':2, 'amount':6.32}, ...]),然后格式化每个项目的金额"值?如果是这样,我该怎么做?
How can I solve the problem whereby the row object values cannot be changed? Could I convert the cursor to a list of dictionaries (one for each row, eg. [{'order_no':1, 'amount':12.1}, {'order_no':2, 'amount':6.32}, ...]), then format the 'amount' value for each item? If so, how can I do this?
是否有更好的解决方案来实现我的目标?任何帮助将不胜感激.
Are there any better solutions for achieving my goal? Any help would be appreciated.
TIA,艾伦
推荐答案
是的:
cur.execute("select order_no, amount from orders where cust_id=123")
dictrows = [dict(row) for row in cur]
for r in dictrows:
r['amount'] = format(r['amount'],'%.2f')
还有其他方法,但这种方法似乎是最简单、最直接的一种.
There are other ways, but this one seems the simplest and most direct one.
这篇关于替换所有游标行中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!