在JSP中用bean封裝常用的功能
來源:互聯網
上載者:User
源作者:追風
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();
%>
……