(转载请注明来源)
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 success!";
} 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