从数据库中读取数据

时间:2014-04-21 03:10:03

标签: html jsp

在我的程序中,我让用户将他们的票号输入到一个html表单中,该表单连接到一个jsp页面,该页面应该从数据库中获取信息并将其填充到我创建的表中。相反,我只从我制作的标题打印出来,并在底部按下按钮。它打印出catch语句中的错误代码。有人可以帮我弄清楚如何解决这个问题。我已经把代码弄乱了一段时间了。请帮帮忙?

非常感谢。这是我项目的最后一步......

<HTML>
 <HEAD><TITLE>Ticket Information</TITLE></HEAD>
 <BODY>

 <p>Ticket Information
<%@ page import="java.sql.*" %>
<TABLE BORDER=1 width="75%">
<TR><TH>Ticket</TH><TH>Date</TH><TH>Equipment</TH><TH>Description</TH><TH>Employee</TH><TH>Technician</TH></TR>
<%
  Connection con = null;
  Statement st = null;
  ResultSet rs = null;
  String tix = request.getParameter("Enter Ticket Number");
  String ticketlkup;


  try 
  {
    //load the Driver
    Class.forName("com.mysql.jdbc.Driver").newInstance();

    //Create a connection to the "emp" database
    con = DriverManager.getConnection("jdbc:mysql://localhost/helpdesk?user=root&password=password");

    //Create a Statement object
    st = con.createStatement();

    //Create a ResultSet object and store the results of the query execution
    rs = st.executeQuery("select * from ticket1 where t_id= " + tix +";");




%>
<TR><TD><%= rs.getString("t_id") %></TD>
<TD><%= rs.getString("t_date") %></TD>
<TD><%= rs.getString("t_equipment") %></TD>
<TD><%= rs.getString("t_descript") %></TD>
<TD><%= rs.getString("emp_id") %></TD>
<TD><%= rs.getString("tech_id") %></TD>
</TR>



<%
  } //end of try block
  catch (java.sql.SQLException ex) 
  {
    ex.printStackTrace();
%>
</TABLE>
Ooops, something bad happened:
<%
  } //end of catch block 
  finally
  {
    if (rs != null) rs.close();
    if (st != null) st.close();
    if (con != null) con.close();
  } //end of finally block

%>

</p>

<FORM method="post" action="http://localhost:8080/finalproject/helpdeskhome.html" >
<p>Click on the button to go back to the main page </p>
<button type="submit">Home</button>

</FORM>
</BODY>
</HTML>

1 个答案:

答案 0 :(得分:0)

在开始使用结果集之前,您必须调用rs.next(),因为当您刚执行查询时,您还没有在第一行。如果没有行(或没有行),rs.next()显然会返回false

  try
  {
    ...
    rs = st.executeQuery("select * from ticket1 where t_id= " + tix +";");
    if(rs.next())
    {
   %>
    <TR><TD><%= rs.getString("t_id") %></TD>
    <TD><%= rs.getString("t_date") %></TD>
    <TD><%= rs.getString("t_equipment") %></TD>
    <TD><%= rs.getString("t_descript") %></TD>
    <TD><%= rs.getString("emp_id") %></TD>
    <TD><%= rs.getString("tech_id") %></TD>
    </TR>
  <%
    } //end of if
    else
    {
        out.print("<TR><TD colspan='6'>No Rows</TD></TR>");
    }
  } //end of try block