views:

49

answers:

2

i have write code hear i have problem of selecting value from sqlserver i pass the value from nrno is geting by another page

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
</head>
<body>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
String AppURL = request.getContextPath() ;
String thisFile = AppURL+request.getServletPath() ;
int nrno = 0;
try
{
 nrno = Integer.parseInt(request.getParameter("rno"));
}
catch(NumberFormatException ex)
{ 
    nrno = 0;
}
%>
<td>This Is In RoolNo :- <%=nrno%> </td><br>
<%
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/sample", "sa", "sa1234");
java.sql.Statement stmt = conn.createStatement();
java.sql.ResultSet rslt = stmt.executeQuery(" SELECT * FROM student where rno = nrno");
while(rslt.next())
     { 
       int id = rslt.getInt(1);
      int rno = rslt.getInt(4);
       String name = rslt.getString(2); 
      String city = rslt.getString(3);
      out.println(id +"<br>" +" " +name + " "+"<br>" + city +"<br>" + rno + "<br>"); 
     }
rslt.close();
stmt.close();
conn.close();
%>
</body>
</html>
+2  A: 

the problem is here:

java.sql.ResultSet rslt = stmt.executeQuery(" SELECT * FROM student where rno = nrno");

this results in passing a string SELECT * FROM student where rno = nrno to sqlServer which is not what you want.

you can change it as specified by Richie to

`java.sql.ResultSet rslt = stmt.executeQuery (" SELECT * FROM student where rno =" +` nrno);

Or better use parametrised call as the first approach may be prone to sql Injection

PreparedStatement st = conn.prepareStatement(
            "SELECT * FROM student where rno = ?");
        st.setInt(1, nrno);

In your case you are parssing nrno to int so probably there is no issue with sql injection but it is saver to user parametrised approach anyway (say the parameter type changes to string in some future release)

kristof
+1 for parameterised queries (could we have a quick example?). Building query strings with literal values from variables isn't a good idea!
bobince
thanks for the comment bobince, updated my answer to add the code example.
kristof
+2  A: 
java.sql.ResultSet rslt = stmt.executeQuery(" SELECT * FROM student where rno = nrno");

You might want to change that to

java.sql.ResultSet rslt = stmt.executeQuery (" SELECT * FROM student where rno =" + nrno);

coz "nrno" is a variable..

Hope this helps you out...

cheers,

RDJ

Richie