1. Create a bean
Package guestbook;
Import java. SQL .*;
/**
* Title: connect to the database with JavaBean
* Description: encapsulate common database functions with bean and declare the bean in JSP.
* Copyright: Copyright (c) 2001
* Company: Speed Network Team
* Editor: Speed Network Group
* Version 1.0
*/
Public class SQL _data
{
String sdbdriver = "Sun. JDBC. ODBC. jdbcodbcdriver ";
String sconnstr = "JDBC: ODBC: Guestbook ";
Connection conn = NULL;
Resultset rs = NULL;
Public SQL _data ()
{
Try {
Class. forname (sdbdriver );
}
Catch (Java. Lang. classnotfoundexception E)
{
System. Err. println ("SQL _data ():" + E. getmessage ());
}
}
Public void executeinsert (string SQL)
{
Try
{
Conn = drivermanager. getconnection (sconnstr );
Statement stmt = conn. createstatement ();
Stmt.exe cuteupdate (SQL );
}
Catch (sqlexception ex)
{
System. Err. println ("SQL _data.executeupdate:" + ex. getmessage ());
}
}
Public resultset executequery (string SQL)
{
Rs = NULL;
Try
{
Conn = drivermanager. getconnection (sconnstr );
Statement stmt = conn. createstatement ();
Rs1_stmt.exe cutequery (SQL );
}
Catch (sqlexception ex)
{
System. Err. println ("SQL _data.executequery:" + ex. getmessage ());
}
}
Public void executedelete (string SQL)
{
Try
{
Conn = drivermanager. getconnection (sconnstr );
Statement stmt = conn. createstatement ();
Stmt.exe cuteupdate (SQL );
}
Catch (sqlexception ex)
{
System. Err. println ("SQL _data.executedelete:" + ex. getmessage ());
}
}
}
2. Declare bean in JSP:
......
<JSP: usebean id = "sqlbean" Scope = "session" class = "guestbook. SQL _data"/>
<%! String SQL, name; %>
<%
SQL = "select * from table ";
Resultset rsw.sqlbean.exe cutequery (SQL );
While (Rs. NEX ()){
Name = Rs. getstring ("name ")
}
%>
......
Name: <% = Name %>
......
<%
Rs. Close ();
%>
......