<%@page import="java.sql.*"
import ="java.util.*"
import ="java.io.*"
contentType="text/html; charset=gb2312"
%>
<html>
<head>
<title>使用MYsql數據庫</title>
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
</head>
<body>
<p align="center"><u><font size="5" face="華文新魏">使用JSP讀取Mysql數據庫</font></u></p>
<%!
String host="localhost"; //數據庫主機
String database="pinghui"; //數據庫名
String user="test"; //用戶名
String pass=""; //口令
%><% java.sql.Connection sqlConn; //數據庫連接對象
java.sql.Statement sqlStmt; //語句對象
java.sql.ResultSet sqlRst; //結果集對象
//登記JDBC驅動對象
Class.forName ("org.gjt.mm.mysql.Driver").newInstance ();
//連接數據庫
sqlConn= java.sql.DriverManager.getConnection ("jdbc:mysql://"+host+"/"+database,user,pass);
//創建語句對象
sqlStmt=sqlConn.createStatement (java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);
//執行Sql語句
String sqlQuery="select count(*) from comment";
sqlRst=sqlStmt.executeQuery (sqlQuery);
sqlRst.next();
int count=sqlRst.getInt(1); //取得總的留言記錄數
sqlQuery="select * from comment order by userid desc;";
sqlRst=sqlStmt.executeQuery (sqlQuery); //執行SQL語句
%>
總共有<%=count%>條留言
<table border="1" width="100%" bordercolorlight="#CC99FF" cellpadding="2" bordercolordark="#FFFFFF" cellspacing="0">
<tr>
<td align="center"> ID</td>
<td align="center">昵稱</td>
<td align="center">性別</td>
<td align="center">地址</td>
<td align="center">IP地址</td>
<td align="center">郵編</td>
<td align="center">Oicq</td>
<td align="center">ICQ</td>
<td align="center">電話</td>
<td align="center">留言</td>
<td align="center">時間</td>
</tr>
<% while (sqlRst.next()) { //取得下一條記錄 %>
<tr><!--顯示記錄-->
<td><%=sqlRst.getString("userid")%></td>
<td><%=sqlRst.getString("username")%></td>
<td><%=sqlRst.getString("sex")%></td>
<td><%=sqlRst.getString("address") %></td>
<td><%=sqlRst.getString("ip") %></td>
<td><%=sqlRst.getString("post")%></td>
<td><%=sqlRst.getString("oicq")%></td>
<td><%=sqlRst.getString("icq")%></td>
<td><%=sqlRst.getString("telnumber")%></td>
<td><%=sqlRst.getString("comment")%></td>
<td><%=sqlRst.getString("time") %></td>
</tr>
<% } %>
</table>
</body>
<%
//關閉結果集對象
sqlRst.close();
//關閉語句對象
sqlStmt.close ();
//關閉數據庫連接
sqlConn.close();
%>