Using beans in JSP to encapsulate the common features of a database

Source: Internet
Author: User
Tags getmessage odbc stmt
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 ();

%>

......

 








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.