jsp+beans实现读取数据库的例子

发表于:2007-07-04来源:作者:点击数: 标签:
(转载请注明来源) From: http://aspfans.yeah.net 需要用到两个程序,jsp文件和数据库操作的java bean Select.jsp html head titleSelect everything from a database/title /head body jsp:useBean id="select" class="DataBaseSelect" scope="request" /be
(转载请注明来源)
From: http://aspfans.yeah.net
需要用到两个程序,jsp文件和数据库操作的java bean

Select.jsp

<html>
<head>
<title>Select everything from a database</title>
</head>
<body>

<jsp:useBean id="select" class="DataBaseSelect" scope="request">
</bean>

<% out.print(select.connect()); %>


<% out.print(select.select()); %>

<p>Format results



<%@ page import="java.util.Vector" %>
<% Vector aResult = select.getResult(); %>

<table>
<% for (int i=0; i < aResult.size(); i++) { %>
<tr>
<td>
<% out.print(aResult.elementAt(i)); %>
</td>
</tr>
<% } %>
</table>

</body>
</html>

DataBaseSelect.java
import java.sql.*;
import java.util.Vector;
public class DataBaseSelect {

private Vector result;

public DataBaseSelect() {
result = new Vector();
} // constructor DataBaseSelect

public String connect() {
try {
Class.forName("a jdbc driver").newInstance();
return "Driver Loaded!";
} catch (Exception E) {
return "Unable to load driver.";
}
}

public String select() {
try {
Connection C = DriverManager.getConnection("database connection string");

Statement Stmt = C.createStatement();

ResultSet myResult = Stmt.executeQuery("SELECT acolumn from atable");

while (myResult.next()) {
result.addElement(myResult.getString(1));
}

// Clean up
myResult.close();
Stmt.close();
C.close();
return "Connection Suclearcase/" target="_blank" >ccess!";
} catch (SQLException E) {
return "SQLException: " + E.getMessage();
}
}

/**
* Accessor for result
**/
public Vector getResult() {
return result;
}

/**
* Mutator for result
**/
public void setResult(Vector avector) {
result = avector;
}

} // class DataBaseSelect

(转载请注明来源)
From: http://aspfans.yeah.net

原文转自:http://www.ltesting.net