gpt4 book ai didi

java - 为什么有 Postgres 异常?

转载 作者:行者123 更新时间:2023-11-29 13:32:56 24 4
gpt4 key购买 nike

下午好。我尝试从 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 注入(inject)的攻击。请求信息的正确方法是使用 prepared statements和参数:

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 与数据库对话需要大量的样板代码。不,“明显”的解决方案是错误的!错误的!错了!

关于java - 为什么有 Postgres 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19538962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com