how to retrieve and add data to a database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gavy7210
    New Member
    • Aug 2009
    • 10

    how to retrieve and add data to a database

    hello friends
    i am new to struts.

    i want to add the user information in the database and then display it back to him.

    i am using struts 1.2,Eclipse Platform Version: 3.4.2,mySql 5.0.1,jdk 1.5..

    i have created a form bean to get the data from the user.
    then in my action class i m trying to get a database connection and adding the values of the user. and i also wanna show them back to him.
    its a dummy project for my learning(to get an insight into struts)
    the code is as follows.

    m sure the mistake is a silly one but as of now i am lost.
    please help

    Code:

    register.jsp
    Code:
    <%@ taglib uri="/WEB-INF/tlds/struts-html.tld" prefix="html" %>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
      <title>Registration Page</title>
      <link href="example.css" rel="stylesheet" type="text/css" />
    </head>
    
    <body>
    
    <div id="top">
    <table border="0">
    <tr>
    <td width="250">	
    		<img src="car.jpg"/>	</td>
    <td width="250">	<h1 align="center"><font face="courier new" >thecarsite</font></h1>	</td>
    <td width="250">     <h2 align="right"><html:link forward="index">Home</html:link></h2></td>
    </tr>
    </table>
    <hr width="100%">
    </div>
    
    <div id="restpage" >
    <html:errors/>
    <html:form   action="/register">
    
    <h2>USER DETAILS:</h2>
    <font size="-1" color="red">*</font>FIRST NAME <html:text property="fname" size="15" maxlength="20"/>&nbsp;&nbsp;&nbsp;&nbsp;
    MIDDLE NAME <html:text property="mname" size="10" maxlength="20"/>&nbsp;&nbsp;&nbsp;&nbsp;
    <font size="-1" color="red">*</font>LAST NAME <html:text property="lname" size="15" maxlength="20"/><br><br>
    DATE OF BIRTH <html:text property="dob" size="10" maxlength="10"/>(dd/mm/yyyy)<br><br>
    ADDRESS <html:text property="add" size="30" maxlength="50"/>&nbsp;&nbsp;&nbsp;&nbsp;
    CITY <html:text property="city" size="15" maxlength="20"/>&nbsp;&nbsp;&nbsp;&nbsp;
    STATE <html:text property="state" size="15" maxlength="20"/><br><br>
    ZIP <html:text property="zip" size="6" maxlength="6"/>&nbsp;&nbsp;&nbsp;&nbsp;
    CONTACT NO <html:text property="cno" size="10" maxlength="10"/>
    <font size="-1" color="red">*</font>EMAIL ID <html:text property="email" size="15" maxlength="20"/><br>
    
    <h2>LOGIN DETAILS</h2>
    <font size="-1" color="red">*</font>USER NAME &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <html:text property="uid" size="15" maxlength="20"/><br>
    <font size="-1" color="red">*</font>PASSWORD &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <html:password property="psswd" size="15" maxlength="20"/><br>
    <font size="-1" color="red">*</font>RE-TYPE PASSWORD <html:password property="rpsswd" size="15" maxlength="20"/><br><br><br>
    <center>
    <font size="5" color="red">(*) Mandatory Fields</font><br><br>
    </center>
    <html:submit value="Submit" /><br>
    
    </html:form >
    </div>
    </body>
    
    
    </html>

    RegisterForm.ja va
    Code:
    package register;
    
    import javax.servlet.http.HttpServletRequest;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionMessage;
    
    
    public class RegisterForm extends ActionForm {
    	
    	String Fname,Lname,Email,Uid,Psswd,Rpsswd,mname,dob,add,cno,state,city,zip;
    	
    	
    
    	public String getDob() {
    		return dob;
    	}
    
    	public void setDob(String dob) {
    		this.dob = dob;
    	}
    
    	public String getAdd() {
    		return add;
    	}
    
    	public void setAdd(String add) {
    		this.add = add;
    	}
    
    	
    	public String getCno() {
    		return cno;
    	}
    
    	public void setCno(String cno) {
    		this.cno = cno;
    	}
    
    	public String getState() {
    		return state;
    	}
    
    	public void setState(String state) {
    		this.state = state;
    	}
    
    	public String getCity() {
    		return city;
    	}
    
    	public void setCity(String city) {
    		this.city = city;
    	}
    
    	public String getZip() {
    		return zip;
    	}
    
    	public void setZip(String zip) {
    		this.zip = zip;
    	}
    
    	public String getMname() {
    		return mname;
    	}
    
    	public void setMname(String mname) {
    		this.mname = mname;
    	}
    
    	public String getFname() {
    		return Fname;
    	}
    
    	public void setFname(String fname) {
    		Fname = fname;
    	}
    
    	public String getLname() {
    		return Lname;
    	}
    
    	public void setLname(String lname) {
    		Lname = lname;
    	}
    
    	public String getEmail() {
    		return Email;
    	}
    
    	public void setEmail(String email) {
    		Email = email;
    	}
    
    	public String getUid() {
    		return Uid;
    	}
    
    	public void setUid(String uid) {
    		Uid = uid;
    	}
    
    	public String getPsswd() {
    		return Psswd;
    	}
    
    	public void setPsswd(String psswd) {
    		Psswd = psswd;
    	}
    
    	public String getRpsswd() {
    		return Rpsswd;
    	}
    
    	public void setRpsswd(String rpsswd) {
    		Rpsswd = rpsswd;
    	}
    	public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)
    	{
    		ActionErrors actionErrors= new ActionErrors();
    		if(getFname()=="")
    		{
    			actionErrors.add("Fname", new ActionMessage("fname.required"));
    		}
    		if(getLname()=="")
    		{
    			actionErrors.add("Lname", new ActionMessage("lname.required"));
    		}
    		if(getEmail()=="")
    		{
    			actionErrors.add("Email", new ActionMessage("email.required"));
    		}
    		if(getUid()=="")
    		{
    			actionErrors.add("Username",new ActionMessage("uid.required"));
    		}
    		
    		if(getPsswd()=="")
    		{
    			actionErrors.add("Password",new ActionMessage("psswd.required"));
    		}
    		else if (getUid().equals(getPsswd()))
    		{
    			actionErrors.add("Unp",new ActionMessage("value.match"));
    		}
    		if(getRpsswd()=="")
    		{
    			actionErrors.add("Password",new ActionMessage("rpsswd.required"));
    		}
    		if ( getRpsswd().equals(getPsswd()) )
    		{}else{
    			actionErrors.add("Unp",new ActionMessage("value.notmatch"));
    		}
    		
    		return actionErrors;
    	}
    
    }
    RegisterAction. java
    Code:
    package register;
    
    import java.sql.Connection;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.sql.DataSource;
    
    import register.RegisterDAO;
    
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    
    public class RegisterAction extends Action {
    
    	public ActionForward execute(ActionMapping mapping, ActionForm form,
    			HttpServletRequest request, HttpServletResponse response)
    	throws Exception {
    		RegisterForm form1= (RegisterForm)form;
    		RegisterDAO registerDAO = new RegisterDAO();
    		User user = new User();
    		
    		Connection con = null; 
            DataSource ds = null; 		
    		
            ds = getDataSource(request);
            
    		String fname= form1.getFname();
    		String mname= form1.getMname();
    		String lname= form1.getLname();
    		String dob= form1.getDob();
    		String address= form1.getAdd();
    		String city= form1.getCity();
    		String state= form1.getState();
    		String zip= form1.getZip();
    		String cno= form1.getCno();
    		String email= form1.getEmail();
    		String uid= form1.getUid();
    		String psswd= form1.getPsswd();
    		user= RegisterDAO.setRecord(con,user);
    		user= RegisterDAO.getRecord(con,user);
    				
    		
    		registerDAO.closeConnection(con);
    				
    		
    
    		return mapping.findForward("success");
    	}
    }
    RegisterDAO.jav a
    Code:
    package register;
    
    import register.User;
    
    import java.sql.Connection; 
    import java.sql.PreparedStatement;
    import java.sql.ResultSet; 
    import java.sql.SQLException;
    import java.util.ArrayList;
    
    import javax.sql.DataSource; 
    
    public class RegisterDAO {
    
    	
    	public Connection getConnection(DataSource carsite) { 
    		Connection con = null; 
    		DataSource ds = carsite; 
    		try { 
    			con = ds.getConnection(); 
    		} catch (SQLException e) { 
    			e.printStackTrace(); 
    		} 
    		return con; 
    	}
    	public void closeConnection(Connection con) { 
    		try { 
    			con.setAutoCommit(true);
    			con.close(); 
    		} catch (SQLException e) { 
    			e.printStackTrace(); 
    		} 
    	}
    	public static User getRecord(Connection con, User user) { 
    		ArrayList<User> list= new ArrayList<User>();
    		String qry = "select * from register where username=?"; 
    		ResultSet resultSet = null; 
    
    		try { 
    			PreparedStatement pstat = con.prepareStatement(qry); 
    			pstat.setString(11, user.getUid()); 
    			resultSet = pstat.executeQuery(); 
    			while (resultSet.next()) { 
    
    				user.setFname(resultSet.getString("fname")); 
    				user.setMname(resultSet.getString("mname")); 
    				user.setLname(resultSet.getString("lname")); 
    				user.setDob	 (resultSet.getString("dob")); 
    				user.setAdd  (resultSet.getString("address")); 
    				user.setCity (resultSet.getString("city")); 
    				user.setState(resultSet.getString("state"));
    				user.setFname(resultSet.getString("zip"));
    				user.setFname(resultSet.getString("cno"));
    				user.setFname(resultSet.getString("email"));
    
    				list.add(user);
    			} 
    
    		} catch (SQLException e) { 
    			e.printStackTrace(); 
    		} return user;
    	}
    
    
    	public static User setRecord(Connection con, User user) {
    		
    		String qry = "INSERT INTO register VALUES('" + user.getFname() + "','"
    					+ user.getMname() + "','" + user.getLname() + "' ,'" + user.getDob() + " ','" + user.getAdd()
    					+ "','" + user.getState() + "' ,'" + user.getZip() + "','" + user.getCno() + "','"
    					+ user.getEmail() + "','" + user.getUid() + "','" + user.getPsswd() + "')";
    
    			
    		ResultSet resultSet = null; 
    
    		try { 
    			// m yet to write the code for this 				
    			} }
    		catch (SQLException e) { 
    				e.printStackTrace();
    		}	
    			return user;
    		
    	}
    	
    }
    User.java
    Code:
    package register;
    
    public class User {
    private String Fname,Lname,Email,Rpsswd,mname,dob,add,cno,state,city,zip,uid,psswd;
    
    public String getPsswd() {
    	return psswd;
    }
    
    public void setPsswd(String psswd) {
    	this.psswd = psswd;
    }
    
    public String getUid() {
    	return uid;
    }
    
    public void setUid(String uid) {
    	this.uid = uid;
    }
    
    public String getFname() {
    	return Fname;
    }
    
    public void setFname(String fname) {
    	Fname = fname;
    }
    
    public String getLname() {
    	return Lname;
    }
    
    public void setLname(String lname) {
    	Lname = lname;
    }
    
    public String getEmail() {
    	return Email;
    }
    
    public void setEmail(String email) {
    	Email = email;
    }
    
    public String getRpsswd() {
    	return Rpsswd;
    }
    
    public void setRpsswd(String rpsswd) {
    	Rpsswd = rpsswd;
    }
    
    public String getMname() {
    	return mname;
    }
    
    public void setMname(String mname) {
    	this.mname = mname;
    }
    
    public String getDob() {
    	return dob;
    }
    
    public void setDob(String dob) {
    	this.dob = dob;
    }
    
    public String getAdd() {
    	return add;
    }
    
    public void setAdd(String add) {
    	this.add = add;
    }
    
    public String getCno() {
    	return cno;
    }
    
    public void setCno(String cno) {
    	this.cno = cno;
    }
    
    public String getState() {
    	return state;
    }
    
    public void setState(String state) {
    	this.state = state;
    }
    
    public String getCity() {
    	return city;
    }
    
    public void setCity(String city) {
    	this.city = city;
    }
    
    public String getZip() {
    	return zip;
    }
    
    public void setZip(String zip) {
    	this.zip = zip;
    }
    
    }
    Also the database is named carsite and it has a table register created in it.
    the struts-config and web xml enteries are error free. i shall post them too if need be.
    please help

    the error is:
    WARNING: Unhandled Exception thrown: class java.lang.NullP ointerException
    Aug 4, 2009 10:28:14 AM org.apache.cata lina.core.Stand ardWrapperValve invoke
    SEVERE: Servlet.service () for servlet action threw exception
    java.lang.NullP ointerException
    at register.Regist erDAO.setRecord (RegisterDAO.ja va:76)
    at register.Regist erAction.execut e(RegisterActio n.java:42)
    at org.apache.stru ts.action.Reque stProcessor.pro cessActionPerfo rm(RequestProce ssor.java:421)
    at org.apache.stru ts.action.Reque stProcessor.pro cess(RequestPro cessor.java:226 )
    at org.apache.stru ts.action.Actio nServlet.proces s(ActionServlet .java:1164)
    at org.apache.stru ts.action.Actio nServlet.doPost (ActionServlet. java:415)
    at javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:709)
    at javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:802)
    at org.apache.cata lina.core.Appli cationFilterCha in.internalDoFi lter(Applicatio nFilterChain.ja va:252)
    at org.apache.cata lina.core.Appli cationFilterCha in.doFilter(App licationFilterC hain.java:173)
    at org.apache.cata lina.core.Stand ardWrapperValve .invoke(Standar dWrapperValve.j ava:213)
    at org.apache.cata lina.core.Stand ardContextValve .invoke(Standar dContextValve.j ava:178)
    at org.apache.cata lina.core.Stand ardHostValve.in voke(StandardHo stValve.java:12 6)
    at org.apache.cata lina.valves.Err orReportValve.i nvoke(ErrorRepo rtValve.java:10 5)
    at org.apache.cata lina.core.Stand ardEngineValve. invoke(Standard EngineValve.jav a:107)
    at org.apache.cata lina.connector. CoyoteAdapter.s ervice(CoyoteAd apter.java:148)
    at org.apache.coyo te.http11.Http1 1Processor.proc ess(Http11Proce ssor.java:869)
    at org.apache.coyo te.http11.Http1 1BaseProtocol$H ttp11Connection Handler.process Connection(Http 11BaseProtocol. java:664)
    at org.apache.tomc at.util.net.Poo lTcpEndpoint.pr ocessSocket(Poo lTcpEndpoint.ja va:527)
    at org.apache.tomc at.util.net.Lea derFollowerWork erThread.runIt( LeaderFollowerW orkerThread.jav a:80)
    at org.apache.tomc at.util.threads .ThreadPool$Con trolRunnable.ru n(ThreadPool.ja va:684)
    at java.lang.Threa d.run(Unknown Source)
    Last edited by gavy7210; Aug 4 '09, 05:41 AM. Reason: wrong file uploaded
  • numberwhun
    Recognized Expert Moderator Specialist
    • May 2007
    • 3467

    #2
    This is a java related question so I will move it to the appropriate forum. If you question is regarding your coding, please be sure to start the thread in the correct forum.

    Regards,

    Jeff

    Comment

    • gavy7210
      New Member
      • Aug 2009
      • 10

      #3
      thank you jeff..
      i was confused so as to where to put it.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Code:
        WARNING: Unhandled Exception thrown: class java.lang.NullPointerException
        Aug 4, 2009 10:28:14 AM org.apache.catalina.core.StandardWrapperValve invoke
        SEVERE: Servlet.service() for servlet action threw exception
        java.lang.NullPointerException
        at register.RegisterDAO.setRecord(RegisterDAO.java:76 )
        at register.RegisterAction.execute(RegisterAction.jav a:42)
        According to the stacktrace something was null which is shouldn't be. A line 76 in method setRecord of class RegisterDAO. According to your code you showed us there is no code at all at that line. You have to figure that out.

        kind regards,

        Jos

        Comment

        • gavy7210
          New Member
          • Aug 2009
          • 10

          #5
          thnks for the reply..
          i ll repost after i code the class completely..
          thereby clearing all the confusions.
          will ask again in time.

          Comment

          • gavy7210
            New Member
            • Aug 2009
            • 10

            #6
            have chnged the package structure (not imp but thought as well let u knw)
            RegisterDAO.jav a
            Code:
            package dao;
            
            import bean.User;
            
            import java.sql.Connection; 
            import java.sql.PreparedStatement;
            import java.sql.ResultSet; 
            import java.sql.SQLException;
            import java.util.ArrayList;
            
            import javax.sql.DataSource; 
            
            public class RegisterDAO {
            
            	
            	public Connection getConnection(DataSource carsite) { 
            		Connection con = null; 
            		DataSource ds =carsite; 
            		try { 
            			con = ds.getConnection(); 
            		} catch (SQLException e) { 
            			e.printStackTrace(); 
            		} 
            		return con; 
            	}
            	public void closeConnection(Connection con) { 
            		try { 
            			con.close(); 
            		} catch (SQLException e) { 
            			e.printStackTrace(); 
            		} 
            	}
            	public static User getRecord(Connection con, User user) { 
            		ArrayList<User> list= new ArrayList<User>();
            		String qry = "select * from register where uid=?"; 
            		ResultSet resultSet = null; 
            
            		try { 
            			PreparedStatement pstat = con.prepareStatement(qry); 
            			pstat.setString(10, user.getUid()); 
            			resultSet = pstat.executeQuery(); 
            			while (resultSet.next()) { 
            
            				user.setFname(resultSet.getString("fname")); 
            				user.setMname(resultSet.getString("mname")); 
            				user.setLname(resultSet.getString("lname")); 
            				user.setDob	 (resultSet.getString("dob")); 
            				user.setAdd  (resultSet.getString("address")); 
            				user.setCity (resultSet.getString("city")); 
            				user.setState(resultSet.getString("state"));
            				user.setFname(resultSet.getString("zip"));
            				user.setFname(resultSet.getString("cno"));
            				user.setFname(resultSet.getString("email"));
            
            				list.add(user);
            			} 
            
            		} catch (SQLException e) { 
            			e.printStackTrace(); 
            		} return user;
            	}
            
            
            	public static User setRecord(Connection con, User user) {
            		
            		String qry = "INSERT INTO register VALUES('" + user.getFname() + "','"
            					+ user.getMname() + "','" + user.getLname() + "' ,'" + user.getDob() + " ','" + user.getAdd()
            					+ "','" + user.getState() + "' ,'" + user.getZip() + "','" + user.getCno() + "','"
            					+ user.getEmail() + "','" + user.getUid() + "','" + user.getPsswd() + "')";
            
            		try { 
            			System.out.println(qry);
            			PreparedStatement pstat = con.prepareStatement(qry);
            			pstat.executeUpdate(qry); 
            			System.out.println("******************************************");
            			System.out.println("Entries are Successfully entered into database");
            			}
            		catch (SQLException e) { 
            				e.printStackTrace();
            		}	
            			return user;
            		
            	}
            	
            }

            now uid is my 10th feild in the table thus i have given the value 10 in pstat.setString ().
            but i m getting an error.

            which is

            java.sql.SQLExc eption: Parameter index out of range (10 > number of parameters, which is 1).
            at com.mysql.jdbc. SQLError.create SQLException(SQ LError.java:910 )
            at com.mysql.jdbc. PreparedStateme nt.setInternal( PreparedStateme nt.java:2715)
            at com.mysql.jdbc. PreparedStateme nt.setString(Pr eparedStatement .java:3546)
            at org.apache.tomc at.dbcp.dbcp.De legatingPrepare dStatement.setS tring(Delegatin gPreparedStatem ent.java:131)
            at dao.RegisterDAO .getRecord(Regi sterDAO.java:40 )
            at action.Register Action.execute( RegisterAction. java:45)
            at org.apache.stru ts.action.Reque stProcessor.pro cessActionPerfo rm(RequestProce ssor.java:421)
            at org.apache.stru ts.action.Reque stProcessor.pro cess(RequestPro cessor.java:226 )
            at org.apache.stru ts.action.Actio nServlet.proces s(ActionServlet .java:1164)
            at org.apache.stru ts.action.Actio nServlet.doPost (ActionServlet. java:415)
            at javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:709)
            at javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:802)
            at org.apache.cata lina.core.Appli cationFilterCha in.internalDoFi lter(Applicatio nFilterChain.ja va:252)
            at org.apache.cata lina.core.Appli cationFilterCha in.doFilter(App licationFilterC hain.java:173)
            at org.apache.cata lina.core.Stand ardWrapperValve .invoke(Standar dWrapperValve.j ava:213)
            at org.apache.cata lina.core.Stand ardContextValve .invoke(Standar dContextValve.j ava:178)
            at org.apache.cata lina.core.Stand ardHostValve.in voke(StandardHo stValve.java:12 6)
            at org.apache.cata lina.valves.Err orReportValve.i nvoke(ErrorRepo rtValve.java:10 5)
            at org.apache.cata lina.core.Stand ardEngineValve. invoke(Standard EngineValve.jav a:107)
            at org.apache.cata lina.connector. CoyoteAdapter.s ervice(CoyoteAd apter.java:148)
            at org.apache.coyo te.http11.Http1 1Processor.proc ess(Http11Proce ssor.java:869)
            at org.apache.coyo te.http11.Http1 1BaseProtocol$H ttp11Connection Handler.process Connection(Http 11BaseProtocol. java:664)
            at org.apache.tomc at.util.net.Poo lTcpEndpoint.pr ocessSocket(Poo lTcpEndpoint.ja va:527)
            at org.apache.tomc at.util.net.Lea derFollowerWork erThread.runIt( LeaderFollowerW orkerThread.jav a:80)
            at org.apache.tomc at.util.threads .ThreadPool$Con trolRunnable.ru n(ThreadPool.ja va:684)
            at java.lang.Threa d.run(Unknown Source)


            the earlier problems wre solved there was alogical error on my part.

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #7
              Originally posted by gavy7210
              Code:
              	public static User getRecord(Connection con, User user) { 
              		ArrayList<User> list= new ArrayList<User>();
              		String qry = "select * from register where uid=?"; 
              		ResultSet resultSet = null; 
              
              		try { 
              			PreparedStatement pstat = con.prepareStatement(qry); 
              			pstat.setString(10, user.getUid());

              now uid is my 10th feild in the table thus i have given the value 10 in pstat.setString ().
              but i m getting an error.

              which is

              java.sql.SQLExc eption: Parameter index out of range (10 > number of parameters, which is 1).
              at com.mysql.jdbc. SQLError.create SQLException(SQ LError.java:910 )
              at com.mysql.jdbc. PreparedStateme nt.setInternal( PreparedStateme nt.java:2715)
              at com.mysql.jdbc. PreparedStateme nt.setString(Pr eparedStatement .java:3546)
              at org.apache.tomc at.dbcp.dbcp.De legatingPrepare dStatement.setS tring(Delegatin gPreparedStatem ent.java:131)
              at dao.RegisterDAO .getRecord(Regi sterDAO.java:40 )
              That PreparedStateme nt has only one parameter (one unquoted question mark) so you can't set parameter #10; it doesn't matter which column in your table it actually is, you are setting the single parameter i.e. #1 just as the error message clearly says.

              kind regards,

              Jos

              Comment

              • gavy7210
                New Member
                • Aug 2009
                • 10

                #8
                hey jos
                thnks for your reply.
                but can u explain it to me more clearly.
                now my aim is to display the data of the logged in user to him(not all users)
                for this i have changed the DAO and action classes as below.

                RegisterDAO.jav a
                package dao;

                import bean.User;

                import java.sql.Connec tion;
                import java.sql.Prepar edStatement;
                import java.sql.Result Set;
                import java.sql.SQLExc eption;
                import java.util.Array List;

                import javax.sql.DataS ource;

                public class RegisterDAO {


                public Connection getConnection(D ataSource carsite) {
                Connection con = null;
                DataSource ds =carsite;
                try {
                con = ds.getConnectio n();
                } catch (SQLException e) {
                e.printStackTra ce();
                }
                return con;
                }
                public void closeConnection (Connection con) {
                try {
                con.close();
                } catch (SQLException e) {
                e.printStackTra ce();
                }
                }
                public static ArrayList<User> getRecord(Conne ction con, User user) {
                ArrayList<User> list= new ArrayList<User> ();
                String qry = "select * from register where username=?";
                ResultSet resultSet = null;

                try {
                PreparedStateme nt pstat = con.prepareStat ement(qry);
                pstat.setString (1, user.getUid());
                resultSet = pstat.executeQu ery();
                while (resultSet.next ()) {

                user.setFname(r esultSet.getStr ing("fname"));
                user.setMname(r esultSet.getStr ing("mname"));
                user.setLname(r esultSet.getStr ing("lname"));
                user.setDob (resultSet.getS tring("dob"));
                user.setAdd (resultSet.getS tring("address" ));
                user.setCity (resultSet.getS tring("city"));
                user.setState(r esultSet.getStr ing("state"));
                user.setZip (resultSet.getS tring("zip"));
                user.setCno (resultSet.getS tring("cno"));
                user.setEmail(r esultSet.getStr ing("email"));
                user.setUid (resultSet.getS tring("fname")) ;
                user.setPsswd(r esultSet.getStr ing("fname"));


                list.add(user);
                }

                } catch (SQLException e) {
                e.printStackTra ce();
                } return list;
                }


                public static User setRecord(Conne ction con, User user) {

                int updateQuery= 0;

                String qry = "INSERT INTO register VALUES('" + user.getFname() + "','" + user.getMname()
                + "','" + user.getLname() + "' ,'" + user.getDob() + " ','" + user.getAdd()
                + "','" + user.getCity() + "','" + user.getState() + "' ,'" + user.getZip() + "','"
                + user.getCno() + "','" + user.getEmail() + "','" + user.getUid() + "','"
                + user.getPsswd() + "')";

                try {
                System.out.prin tln(qry);
                PreparedStateme nt pstat = con.prepareStat ement(qry);
                updateQuery = pstat.executeUp date();
                if (updateQuery != 0)
                {
                System.out.prin tln("********** *************** *************** **");
                System.out.prin tln("Entries are Successfully entered into database");
                }
                }
                catch (SQLException e) {
                e.printStackTra ce();
                }
                return user;

                }

                }
                RegisterAction. java
                package action;

                import java.sql.Connec tion;
                import java.util.Array List;

                import javax.servlet.h ttp.HttpServlet Request;
                import javax.servlet.h ttp.HttpServlet Response;
                import javax.sql.DataS ource;

                import org.apache.stru ts.action.Actio n;
                import org.apache.stru ts.action.Actio nForm;
                import org.apache.stru ts.action.Actio nForward;
                import org.apache.stru ts.action.Actio nMapping;

                import bean.User;
                import dao.RegisterDAO ;
                import form.RegisterFo rm;

                public class RegisterAction extends Action {

                public ActionForward execute(ActionM apping mapping, ActionForm form,
                HttpServletRequ est request, HttpServletResp onse response)
                throws Exception {

                RegisterDAO registerDAO = new RegisterDAO();
                User user = new User();

                DataSource ds = getDataSource(r equest);
                Connection con = ds.getConnectio n();

                RegisterForm form1= (RegisterForm)f orm;

                user.setFname(f orm1.getFname() );
                user.setMname(f orm1.getMname() );
                user.setLname(f orm1.getLname() );
                user.setDob(for m1.getDob());
                user.setAdd(for m1.getAdd());
                user.setAdd(for m1.getCity());
                user.setCity(fo rm1.getCity());
                user.setState(f orm1.getState() );
                user.setZip(for m1.getZip());
                user.setCno(for m1.getCno());
                user.setEmail(f orm1.getEmail() );
                user.setUid(for m1.getUid());
                user.setPsswd(f orm1.getPsswd() );

                user= RegisterDAO.set Record(con,user );
                ArrayList<User> list= RegisterDAO.get Record(con,user );
                request.setAttr ibute("userinfo ", list);

                con.setAutoComm it(true);
                registerDAO.clo seConnection(co n);



                return mapping.findFor ward("success") ;
                }
                }
                viewreginfo.jsp
                <%@ taglib uri="/WEB-INF/tlds/struts-html.tld" prefix="html" %>
                <%@ taglib uri="/WEB-INF/tlds/struts-bean.tld" prefix="bean" %>
                <%@ taglib uri="/WEB-INF/tlds/struts-logic.tld" prefix="logic" %>

                <%@ page language="java" contentType="te xt/html; charset=ISO-8859-1"
                pageEncoding="I SO-8859-1"%>
                <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
                <html>
                <head>
                <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
                <title>The Stored User Information</title>
                </head>
                <body background="nex us.jpg" >
                <div id="top">
                <table border="0">
                <tr>
                <td width="250">
                <img src="car.jpg"/> </td>
                <td width="250"> <h1 align="center"> <font face="courier new" color="white">t hecarsite</font></h1> </td>
                <td width="250"> <h2 align="right">< html:link forward="index" >Home</html:link></h2></td>
                </tr>
                </table>
                <hr width="100%">
                </div>
                The Account information for user
                <div id="restpage" >

                <logic:iterat e id="result" name="form1" property="useri nfo">
                <bean:write name="result" />
                </logic:iterate>

                </div>
                </body>
                </html>

                and am replyin late cuz it was a holiday yesterday(an imp hindu festival called Rakhi).

                hoping for guidance
                Gaurav

                Comment

                • JosAH
                  Recognized Expert MVP
                  • Mar 2007
                  • 11453

                  #9
                  Originally posted by gavy7210
                  hey jos
                  thnks for your reply.
                  but can u explain it to me more clearly.
                  You should read the API documentation for the PreparedStateme nt interface; it explains it all.

                  kind regards,

                  Jos

                  Comment

                  • gavy7210
                    New Member
                    • Aug 2009
                    • 10

                    #10
                    ohk i shall :)
                    regards
                    gaurav

                    Comment

                    Working...