在JSP中用bean封裝常用的技巧
發(fā)表時間:2024-05-25 來源:明輝站整理相關軟件相關文章人氣:
[摘要]1、建立一個Beanpackage guestbook;import java.sql.*;/*** Title:用Javabean連接數(shù)據(jù)庫* Description:用Bean把常用的數(shù)據(jù)庫功能封裝,在JSP中聲明該Bean。* Copyright: Copyright (c) 2001* C...
1、建立一個Bean
package guestbook;
import java.sql.*;
/**
* Title:用Javabean連接數(shù)據(jù)庫
* Description:用Bean把常用的數(shù)據(jù)庫功能封裝,在JSP中聲明該Bean。
* Copyright: Copyright (c) 2001
* Company:極速網(wǎng)絡小組
* 編者:極速網(wǎng)絡小組
* 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();
%>
……