gpt4 book ai didi

java - Servlet 到 MYSQL 连接

转载 作者:行者123 更新时间:2023-11-28 23:28:26 27 4
gpt4 key购买 nike

我正在尝试编写代码来搜索mysql数据库中的员工ID并显示相关内容。

我已经编写了 index.jsp 来输入员工 ID 和 servlet 代码以连接到数据库。我的问题是它没有执行该语句,它抛出一个输出“SQL 语句未执行!”...请帮助我...

    package mypkg;


import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class calandar extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
Connection con = null;


String url = "jdbc:mysql://localhost:3306/escp?useSSL=false";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "password";

String id="";
id=request.getParameter("Id");
String sqlquery="SELECT * FROM employee WHERE emp_id='"+id+"'";

try{
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try{
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sqlquery+id);
while (rs.next()) {

}
}catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}

RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Result.jsp");
dispatcher.forward(request, response);
}

}

最佳答案

这看起来一点都不对:

ResultSet rs = st.executeQuery(sqlquery+id);

由于您已经在查询中连接了 ID,因此它应该只是:

ResultSet rs = st.executeQuery(sqlquery);

另请注意,您的代码很容易受到 SQL 注入(inject)攻击。

关于java - Servlet 到 MYSQL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38319837/

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