在jsp中用bean封装数据库常用的功能
1、建立一个bean
package guestbook;
import java.sql.*;
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();
%>
……
新闻热点
疑难解答