js| Package | data | database
Using beans in JSP to encapsulate the common features of a database
1. Create a Bean
Package guestbook;
import java.sql.*;
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.executeupdate (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 ();
rs=stmt.executequery (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.executeupdate (SQL);
}
catch (SQLException ex)
{
System.err.println ("Sql_data.executedelete:" +ex.getmessage ());
}
}
}
2. Declare the Bean in the JSP:
......
<jsp:usebean id= "Sqlbean" scope= "session" class= "Guestbook.sql_data"/>
<%! String sql,name;%>
<%
Sql= "SELECT * from table";
ResultSet rs=sqlbean.executequery (SQL);
while (Rs.nex ()) {
Name=rs.getstring ("name")
}
%>
......
Name:<%=name%>
......
<%
Rs.close ();
%>
......