当前位置:编程学习 > JSP >>

在JSP中用bean封装常用的功能

源作者:追风
1、建立一个Bean
package guestbook;
import java.sql.*;
/**
* Title:用Javabean连接数据库
* Description:用Bean把常用的数据库功能封装,在JSP中声明该Bean。
* Copyright: Copyright (c) 2001
* Company:极速网络小组
* 编者:极速网络小组
* 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、在JSP中声明Bean:
……
<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();
%>
…… 

补充:Jsp教程,Jsp/Servlet开发工具
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,