Database Reference
In-Depth Information
Discussion
The examples in the preceding sections generate static text, but database content also is
useful for creating hyperlinks. Website URLs or email addresses stored in a table are
easily converted to active links in web pages. You need only properly encode the inforā
mation and add the appropriate HTML tags.
Suppose that a table named
book_vendor
contains bookseller and publisher names and
websites:
mysql>
SELECT * FROM book_vendor ORDER BY name;
+----------------+------------------------+
| name | website |
+----------------+------------------------+
| Amazon.com | www.amazon.com |
| Barnes & Noble | www.barnesandnoble.com |
| O'Reilly Media | www.oreilly.com |
+----------------+------------------------+
This table readily lends itself to the creation of hyperlinked text. To produce a hyperlink
from a row, add the
http://
protocol designator to the
website
value, use the result as
the
href
attribute for an
<a>
anchor tag, and use the
name
value in the body of the tag
to serve as the link label. Here is the result for the Barnes & Noble row:
<a
href=
"http://www.barnesandnoble.com"
>
Barnes
&
Noble
</a>
JSP code to produce an unordered list of hyperlinks from the table contents looks like
this:
<sql:query
dataSource=
"${conn}"
var=
"rs"
>
SELECT name, website FROM book_vendor ORDER BY name
</sql:query>
<ul>
<c:forEach
items=
"${rs.rows}"
var=
"row"
>
<li>
<a
href=
"http://<c:out value="
${row.website}"
/>
">
<c:out
value=
"${row.name}"
/></a>
</li>
</c:forEach>
</ul>
When displayed in a web page, each vendor name in the list becomes an active link that
can be selected to visit the vendor's website. In Python, the equivalent operation looks
like this:
stmt
=
"SELECT name, website FROM book_vendor ORDER BY name"
cursor
=
conn
.
cursor
()
cursor
.
execute
(
stmt
)
items
=
[]
for
(
name
,
website
)
in
cursor
:
items
.
append
(
'<a href="http://
%s
">
%s
</a>'