JSP executeQuery无法正常工作

时间:2013-12-04 08:49:19

标签: oracle jsp executequery

我有一个基本代码,但它不起作用。我不知道为什么。我通过在每行之后打印来检查整个代码,但似乎executequery给了我很多时间。需要专家帮助

<%@ 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 个答案:

答案 0 :(得分:3)

您的陈述可能会引发错误,因为您没有引用文字。

而不是这段代码:

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

尝试:

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

或者更好的是,使用java.sql.PreparedStatement在查询中使用参数。只需谷歌java PreparedStatement,你会发现很多例子。