在JSP中用bean封装常用的技巧
发表时间:2024-01-17 来源:明辉站整理相关软件相关文章人气:
[摘要]1、建立一个Beanpackage guestbook;import java.sql.*;/*** Title:用Javabean连接数据库* Description:用Bean把常用的数据库功能封装,在JSP中声明该Bean。* Copyright: Copyright (c) 2001* C...
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();
%>
……