Use Database First you need to create a database. Let's use MS Access. Make sure
you have MS Access installed on your computer and you know how to configure
it.
in Windows 95/98. you should go into the ODBC32 icon in your control panel,
and add MS Access Drive on System DSN. Then create a database and a table. You
must give a name to your database and to the table. Let's name the database
"my_db.mdb", name the table "members" and the path to this
database is:
C:\Inetpub\wwwroot\my_db.mdb
Let's design a table "members" something like this:
userId |
user |
pass |
page |
00234578 |
John |
John123 |
john.JSP |
-11350986 |
Mike |
Mike456 |
mike.JSP |
98782345 |
Joe |
Joe789 |
joe.JSP |
... |
... |
... |
... |
To open the database, we need the following code.
<%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <%@ page import="java.util.Date" %> <%@ page import="java.util.*" %> <%@ page import="java.text.*" %> <%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:my_db");
Statement stmt = con.createStatement();
%>
Now you have established a connection to the database. To get data from
the database, we can use SQL.
The next statement is combined JSP code and SQL:
String query="select * from members";
ResultSet rs = stmt.executeQuery(query);
You can write records from the database to your web browser;
while(rs.next()){ String user=rs.getString("user"); String pass=rs.getString("pass"); String page=rs.getString("page");
out.println user +", "+pass+", "+page+"<br>"; }
The meaning of the above code is: if the search "rs" does
not reach the end of the table, keep writing the records on web browser.
When you execute the script, all the records of "user" and "pass"
will be retriaved. The below is a complete JSP page using database. Let's
save it as second.JSP:
<%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %>
<%
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:my_db");
Statement stmt = con.createStatement();
String query="select * from members";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){ String user=rs.getString("user"); String pass=rs.getString("pass"); String page=rs.getString("page");
out.println user +", "+pass+", "+page+"<br>"; }
}catch (Exception e) {
out.println("<br><p align=center><font color=red>Connection
can not be created.</font></p>");
}
%>
|