Topic: 关于在struts中对数据库操作的封装问题!

  Print this page

1.关于在struts中对数据库操作的封装问题! Copy to clipboard
Posted by: realnicky
Posted on: 2005-09-15 11:04

在下刚开始学习struts,有个问题向各位问一下:
我把数据库的信息(URL,驱动,USRE)设置在struts_config.xml中,然后在action中用以下方法对数据库操作
javax.sql.DataSource data;
java.sql.Connection conn;
ResultSet rs=null;
try{
data=getDataSource(request,"db");
conn=data.getConnection();
Statement stmt = conn.createStatement();
rs=stmt.executeQuery(sql);
conn.close();
}catch (java.sql.SQLException sqle){
getServlet().log("Connection.process",sqle);
}finally{}

我想把这些数据库的操作封装到一个类里,由于getDataSource()是action中的一个方法,因此我把数据库的操作封装在一个action中,如下:
public class DataconnAction extends Action {

// --------------------------------------------------------- Instance Variables

// --------------------------------------------------------- Methods
public ResultSet executeQuery(HttpServletRequest request,String sql)
{
javax.sql.DataSource data;
java.sql.Connection conn;
ResultSet rs=null;
try{
data=getDataSource(request,"db");
conn=data.getConnection();
Statement stmt = conn.createStatement();
rs=stmt.executeQuery(sql);
conn.close();
}catch (java.sql.SQLException sqle){
getServlet().log("Connection.process",sqle);
}finally{

}
return rs;
}
}

在另外一个action中调用这个方法
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {

DataconnAction conn = new DataconnAction();
String flag="";
LoginForm loginForm = (LoginForm) form;
ResultSet rs =null;
String sql;
sql="select * from crmuser where userid='"+loginForm.getUsername()+"' and userpasswd='"+loginForm.getPassword()+"'";
///javax.sql.DataSource data;
///java.sql.Connection conn;
rs=conn.executeQuery(request,sql);
.....
结果出现这样的错误:
root cause

java.lang.NullPointerException
org.apache.struts.action.Action.getDataSource(Action.java:532)
data.DataconnAction.executeQuery(DataconnAction.java:31)
com.real.struts.action.LoginAction.execute(LoginAction.java:54)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
我实例化类了啊
请大侠指点迷津!

2.Re:关于在struts中对数据库操作的封装问题! [Re: realnicky] Copy to clipboard
Posted by: eter
Posted on: 2005-11-23 11:07

请先确认您是否连接上数据库!


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923