JSP executeQuery not working

3.8k views Asked by At

I have a basic code but its not working. i don't know why. I checked throughout the code by printing after each line but it seems like executequery is giving me hard time. Need help from experts please

<%@ page import="java.net.*, java.io.*, java.sql.*, java.util.*" %>
<%
String url   = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
Connection   con = null;
Statement    stmt =null;
ResultSet    rs=null;
String uname=request.getParameter("uname");
String passwd=request.getParameter("password");

try
{
//*** Load the jdbc-odbc bridge driver
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();

    //*** Attempt to connect to a driver.
    con = DriverManager.getConnection(url, "admin", "admin");

    //***  Create a Statement object so we can submit
    //***  SQL statements to the driver
    stmt = con.createStatement();

    String  query=("select username,password from users where username="+uname);

    //*** execute query and show result
    rs = stmt.executeQuery(query);

    int numCols = rs.getMetaData().getColumnCount();
while (rs.next())
    {
        int i=0;
        for (i=1; i<=numCols; i++)
            out.println(rs.getString(i));
    }

    //*** close connection
    stmt.close();
    con.close();
}
catch (Exception e)
{
    e.printStackTrace();
}
%>
1

There are 1 answers

3
Alen Oblak On BEST ANSWER

Your statement is probably throwing an error because you are not quoting literals.

Instead of this code:

String  query=("select username,password from users where username="+uname);

Try with:

String  query=("select username,password from users where username='"+uname+"'");

Or better yet, use parameters in your queries by using a java.sql.PreparedStatement. Just google for java PreparedStatement and you will find lots of examples.