繁体   English   中英

为什么会有Postgres例外?

[英]Why there is Postgres exception?

下午好。 我尝试从Eclipse的Java代码连接到数据库。 我需要发出请求,并检查在表单中键入的用户名和密码是否彼此匹配。 用户名及其密码的列表位于名为stud_test的数据库中。 我需要运行gradle和tomcat以便检查servlet是否正常工作。 当我这样做并打开所需的页面时,我看到了PSQLExceptions。 我的代码示例如下。 我不明白是什么问题。

public void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException,IOException {

    Connection con;
    ResultSet rs;

    String URL = "jdbc:postgresql://localhost:5432/stud_test";
    String username = request.getParameter("useruser");
    String passwrd = request.getParameter("pass");
    response.setContentType("text/html");

    try {
        con = DriverManager.getConnection(URL, "postgres", "postgres");
        Statement st = con.createStatement();
        st.executeQuery ("SELECT password FROM stud WHERE user = " + username);
        rs = st.getResultSet();

        if (passwrd.equals(rs)){
            request.getServletContext().getRequestDispatcher(
            "/jsp/hello.jsp").forward(request, response);
        }
        else {
            request.getServletContext().getRequestDispatcher("/jsp/fail.jsp").forward(request, response);
        }

        rs.close ();
        st.close ();
    } 

    catch(Exception e) {
        System.out.println("Exception is :" + e);
    }   
}

除了Sergiu已经提到的内容外,以下行不太可能做您想要的事情:

st.executeQuery ("SELECT password FROM stud WHERE user = " + username);

例如,如果用户名是“ carl”,则将以下语句发送到数据库:

SELECT password FROM stud WHERE user = carl

如果没有名为“ carl”的列,则会导致语法错误。 解决此问题的“显而易见”(和错误方法!)将使用

st.executeQuery ("SELECT password FROM stud WHERE user = '" + username + "'");

这可能会(首先)起作用,但使您容易受到SQL注入的攻击。 请求信息的正确方法是使用准备好的语句和参数:

final PreparedStatement stm = connection.prepareStatement(
        "SELECT password FROM stud WHERE user = ?");

try {

    // For each "hole" ("?" symbol) in the SQL statement, you have to provide a
    // value before the query can be executed. The holes are numbered from left to
    // right, starting with the left-most one being 1. There are a lot of "setXxx"
    // methods in the prepared statement interface, and which one you need to use
    // depends on the type of the actual parameter value. In this case, we assign a
    // string parameter:

    stm.setString(1, username);

    final ResultSet rs = stm.executeQuery();

    try {

        if (rs.next()) {

            if (password.equals(rs.getString(1))) {

                 // Yay. Passwords match. User may log in

            }
        }

    } finally {

         rs.close();
    }

} finally {

    stm.close();
}

是的,通过Java中的JDBC与数据库对话需要大量样板代码。 不,“显而易见的”解决方案是错误的! 错误! 错误!

我想你应该有

if (passwrd.equals(rs.getString(1))){ ... }

假设用户字段是数据库中的varchar。

您不能将字符串(passwrd)与ResultSet实例(rs)匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM