?? dbjsp.jsp
字號:
<%@ page contentType="text/html; charset=GBK" %>
<%
/**
* Title: 使用JSP連接數據庫
* Description: 教學示范
* Copyright: Copyright (c) 2003
* Company: 北京師范大學計算機系
* @author 孫一林
* @version 1.0
*/
%>
<html>
<%@ page language="java" import="java.sql.*"%>
<head>
<%
String tableName = request.getParameter("tableName"); //獲取用戶要顯示數據的表名
%>
<title><%=tableName%>表中數據</title>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<%
Connection connection = null; //定義與數據庫進行連接的Connection對象
ResultSet rs = null; //定義數據庫查詢的結果集
Statement statement = null; //定義查詢數據庫的Statement對象
if (tableName.equals("studentbase"))
{
out.println("<h2 align=center>學生基本信息表中的數據</h2>");
}
else if (tableName.equals("studentaddress"))
{
out.println("<h2 align=center>學生地址表中的數據</h2>");
}
else
{
out.println("<h2 align=center>選課信息表中的數據</h2>");
}
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //指定與數據庫連接使用JDBC-ODBC橋驅動程序
String url = "jdbc:odbc:student"; //指定數據源名
connection = DriverManager.getConnection(url); //與數據源建立連接
statement = connection.createStatement(); //創建Statement接口實例
String sql = "select * from " + tableName; //創建取出用戶指定表中所有數據的SQL語句
rs = statement.executeQuery(sql); //將數據存入結果集中
ResultSetMetaData rsData = rs.getMetaData(); //獲取結果集信息
out.println("<table width=75% border=1 align=center><tr>");
for(int i=1; i<=rsData.getColumnCount(); i++) //輸出字段名
{
out.println("<td>" + rsData.getColumnLabel(i) + "</td>");
}
out.println("</tr>");
while(rs.next()) //輸出表中數據
{
out.println("<tr>");
for(int i=1; i<=rsData.getColumnCount();i++)
{
out.println("<td>" + rs.getString(i) + "</td>");
}
out.println("</tr>");
}
out.println("</table>");
}
catch(SQLException ex){ //捕捉異常
System.out.println("\nERROR:----- SQLException -----\n");
while (ex != null) {
System.out.println("Message: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("ErrorCode: " + ex.getErrorCode());
ex = ex.getNextException();
}
}
catch(Exception ex ) {
ex.printStackTrace();
}
finally {
try {
if(statement != null)
{
statement.close(); //關閉Statement接口實例
}
if(connection != null)
{
connection.close(); //關閉Connection接口實例
}
}
catch (SQLException ex) {
System.out.println("\nERROR:----- SQLException -----\n");
System.out.println("Message: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("ErrorCode: " + ex.getErrorCode());
}
}
%>
</table></body>
</html>
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -