简体   繁体   English

如何使用jsp从表中检索数据?

[英]how to retrieve data from table using jsp?

I am Trying to retrieve data from questions table but this below code is not showing an output. 我正在尝试从问题表中检索数据,但是下面的代码未显示输出。

index.jsp 的index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*" %>


<%  
Connection con = null;  
Statement st   = null;
ResultSet rs   = null;

try{
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/users","root", "1234");
String qry = "SELECT * FROM questions";
rs = st.executeQuery(qry);

while(rs.next()){
   out.println("Email :" + rs.getString(2) + "<br>");
   out.println("Title :" + rs.getString(3) + "<br>");
   out.println("Description :" + rs.getString(4) +"<br>");
}
}
catch(Exception ex){}
%>    

问题表截图

输出屏幕截图

What is out.println? 什么是out.println? that's not how you output using scriptlets. 那不是您使用scriptlet输出的方式。 it should look something like this: 它应该看起来像这样:

        while(rs.next()){
           %>
           <%="Email :" + rs.getString(2) + "<br>"%>
           <%="Title :" + rs.getString(3) + "<br>"%>
           <%="Description :" + rs.getString(4) +"<br>"%>
           <%
        }

And most people would say to not use scriptlets to begin with. 而且大多数人会说从一开始就不使用脚本。

If that doesn't fix the problem, you might have caught an exception. 如果那不能解决问题,则可能是您捕获了异常。 Try and output the exception like this: 尝试输出如下异常:

   catch(Exception ex){%><%=ex.toString()%><%}

It looks like you have a java.lang.NullPointerException, so you have to figure out which object you are trying to use is null. 看起来您有一个java.lang.NullPointerException,因此您必须弄清楚要使用的对象为null。 Looking at your code, it looks like you never initialize your Statement st . 查看您的代码,似乎您从未初始化过Statement st Try adding in st = con.createStatement() after the line that says con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/users","root", "1234"); 尝试在显示con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/users","root", "1234");的行之后添加st = con.createStatement() con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/users","root", "1234");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM