2009年7月5日 星期日

簡意的WEB版SQL練習程式

看了許久,JSP終於看了一半上下了,雖然MySQL的基本應用大致上都會了,但多看一次就多一次收獲,所以就少稍為K一下,書附範例中,有附簡單的WEB版的練習介面,不過老是用別人的,自己怎麼會進步,所以我自己也寫了一個,我是用JNDI的方式去寫的:

<%@page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*, javax.sql.*, javax.naming.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%! Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;

public void jspInit() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

public void jspDestory() {
try {
stmt.close();
rs.close();
con.close();
} catch (Exception e) {
}
}
%>
<% request.setCharacterEncoding("UTF-8");%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<table border="1">
<tbody>
<tr>
<td><center>[Result]</center>
<%
if (request.getParameter("client") != null) {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?user=root&password=111111");
stmt = con.createStatement();
rs = stmt.executeQuery(request.getParameter("client"));
rsmd = rs.getMetaData();
%>
<table border="1">
<thead>
<tr>
<%
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
%>
<th><%=rsmd.getColumnLabel(i)%></th>
<%
}
%>
</tr>
</thead>
<tbody>
<%
while (rs.next()) {
%>
<tr>
<%
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
%>
<td><%=rs.getString(i)%></td>
<%
}
%>
</tr>
<%
}
%>
</tbody>
</table>
<%
}
%>
</td>
</tr>
<tr>
<td><form action="sqlTool.jsp" method="POST">
Practice area:<br>
<textarea name="client" rows="10" cols="50"><%=request.getParameter("client")%></textarea>
<input type="submit" value="Test" name="OK" /></form></td>
</tr>
</tbody>
</table>
</body>
</html>

沒有留言: