无法通过 eclipse 上的"Run on server"选项执行 SQL



我正在尝试让servlet程序与数据库连接并执行操作。在eclipse中,当我将连接和查询放在main((方法中并选择"作为java应用程序运行";它正在工作,数据库正在更新,然而,当我使用";在服务器上运行";并将查询放入doGet((方法中,servlet正在运行,html正在浏览器中更新,但数据库中没有进行更新。我还尝试将代码放入main方法中,并通过doGet((调用main((,但没有成功。

html文件:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Register</title>
</head>
<body>
<form action="register" method="get">
<label for="uname">Username:</label>
<input type="text" name="uname">
<label for="pwd">Password:</label>
<input type="text" name="pwd">
<button type="submit">Register</button>
</form>
</body>
</html>

doGet((方法:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
PrintWriter pw = response.getWriter();
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd");
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/advjavada", "root", "");
if(!con.isClosed()) {
System.out.println("Connection SUCCESSFUL!");
PreparedStatement ps = con.prepareStatement("insert into userdata(uname, pwd) value('sample2', 'sampass2');");
//ResultSet rs = ps.executeQuery();
ps.executeQuery();
}
else {
System.out.println("Connection FAILED!");
}
}
catch (Exception e) {
System.err.print(e.getMessage());
}
pw.println("<h1>Hello, " + uname + "!</h1><p>Registration Successful</p>");
pw.close();
}

Tahir Hussain Mir对这个问题的回答解决了这个问题。事实证明,这是部署过程中的一个问题,其中SQL的外部jar文件用于编译,但在运行时不包括在内。要解决此问题:将.jar文件添加到Project > Properties下的Deployment Assembly中。

最新更新