js|封装源作者:追风
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中用bean封装常用的功能
80酷酷网 80kuku.com