我想在以下index.html页面的<td>
中显示数据库中的每一行:
$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
<tr>
<th>Name</th>
<th>address</th>
<th>number</th>
</tr>
<tr>
<td>//want name here</td>
<td>//address here</td>
<td>//number here</td>
</tr>
</table>
app.py代码:
import web
import MySQLdb
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="a", newname="s", number="d")
conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
x = conn.cursor()
x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name))
conn.commit()
items = x.fetchall()
for row in items:
conn.rollback()
conn.close()
return render.index(items)
if __name__ == "__main__":
app.run()
答案 0 :(得分:1)
项(获取的结果)将是一个元组数组。按原样返回数组,在html上显示整个数据,HTML只渲染一次。
app.py代码
import web
import MySQLdb
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="a", newname="s", number="d")
conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
x = conn.cursor()
x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name))
items = x.fetchall()
conn.close()
return render.index(items) // return the array of results as a whole
if __name__ == "__main__":
app.run()
在index.html上
$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
<tr>
<th>Name</th>
<th>address</th>
<th>number</th>
</tr>
$for row in items:
<tr>
<td>$row[0]</td>
<td>$row[1]</td>
<td>$row[2]</td>
</tr>
</table>
Iterate over the items and display them