Using beans in JSP to encapsulate common features

Source: Internet
Author: User
Tags getmessage odbc stmt
js| package source Author: Herd

1. Create a Bean



Package guestbook;
Import java.sql.*;
/**
* Title: Connect the database with JavaBean
* Description: Encapsulates the commonly used database functionality in a bean and declares the bean in a JSP.
* Copyright:copyright (c) 2001
* Company: Speed Network Group
* 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.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 ();
%>
......


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.