【发布时间】:2021-01-01 09:06:03
【问题描述】:
我正在尝试在浏览器中打印一个表格,并从数据库中获取数据。代码在 jsp 文件中。
我的输出如下所示:
它仍然缺少表中的值。现在我想知道为什么没有从表中获取数据。我检查了数据,表格中填满了值。
到目前为止,这是我在 jsp 文件中的代码:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
String id = request.getParameter("userid");
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "store";
String userid = "root";
String password = "";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Retrieve data from database in jsp</h1>
<table border="1">
<tr>
<th>Name</th>
<th>Strasse</th>
<th>PLZ</th>
<th>Ort</th>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select * from kunde";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("name") %></td>
<td><%=resultSet.getString("strasse") %></td>
<td><%=resultSet.getString("plz") %></td>
<td><%=resultSet.getString("ort") %></td>
</tr>
<%
}
connection.close();
}
catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
在日志文件中,我发现了以下两条错误消息:
An error occurred at line: [41] in the jsp file: [/index.jsp]
userid cannot be resolved to a variable
38:
39: <%
40: try{
41: connection = DriverManager.getConnection(connectionUrl+database, userid, password);
42: statement=connection.createStatement();
43: String sql ="select * from kunde";
44: resultSet = statement.executeQuery(sql);
Stacktrace:] with root cause
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: [41] in the jsp file: [/index.jsp]
userid cannot be resolved to a variable
38:
39: <%
40: try{
41: connection = DriverManager.getConnection(connectionUrl+database, userid, password);
42: statement=connection.createStatement();
43: String sql ="select * from kunde";
44: resultSet = statement.executeQuery(sql);
和
[Warning] Access denied for user 'XY'@'localhost' (using password: NO)
【问题讨论】:
-
你确定表名是对的吗?它有数据吗?
-
只是提醒一下,不再推荐使用 Scripplets。
-
@Swati 是的,我三重检查并添加了一张图片,您可以在其中看到表格中的数据。
-
检查你的服务器日志看看有没有错误?
-
我检查了日志,我没有获得对数据库内容的权限:[警告] 用户 'XY'@'localhost' 的访问被拒绝(使用密码:否)通常它应该与 root 连接不是 XY。你知道怎么改吗?