Servlet到MYSQL的连接

时间:2016-07-12 04:02:27

标签: java mysql jsp servlets

我正在尝试编写代码来搜索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); 
}

}

1 个答案:

答案 0 :(得分:1)

这看起来并不正确:

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

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

ResultSet rs = st.executeQuery(sqlquery);

另请注意,您的代码对SQL注入攻击持开放态度。