【问题标题】:retrieve of data from oracle从 oracle 中检索数据
【发布时间】:2016-05-07 14:48:32
【问题描述】:

我在 oracle 数据库中有一个名为 category 的表,在这个类别表中我有 c_nm 列,数据是 category1,category2,category3,......等等 我希望所有这些数据都存储在我的 jsp 页面上的数组或字符串中。 示例:

<%@ include file"connection.jsp"%> // for connecting to data base 
<%! String S1[]= new String[]%> declare a string

<%
rs=stat.executeQuery("select * from category ");
while(rs.next()){
s1[]=rs.getString(c_nm);
} 
%>

这是正确的编码还是我应该选择另一种方法来做到这一点?

【问题讨论】:

  • 有什么问题?这段代码能编译吗?
  • 只是为了理解正确。您有一个名为“category”的数据库,其中有一个名为“category”的表,其中有一个名为“c_nm”的列,其值为“category1”、“category2”、...?
  • 我没有得到数组中的所有类别是不是在声明数组时有问题
  • 不要不要将 SQL(或 Java)代码放入 JSP。并且不要从 JSP 中启动数据库连接。这真是糟糕的编码风格。
  • 完成后关闭结果集很重要。使用try (ResultSet rs = stat.executeQuery("select * from category")) { /* ...process results... */ }。 (这称为“try-with-resources 块”,它确保在最后调用结果集的 close 方法——即使抛出异常也是如此。)

标签: java oracle jsp


【解决方案1】:

如果您想要您的类别列表,您需要遍历您的结果,并将其添加到List。你会做一个列表,因为你不需要事先知道你有多少类别。

rs=stat.executeQuery("select * from category ");
List<String> categories = new ArrayList<>();
while (rs.next()) {
  categories.add(rs.getString(c_nm));
}

然后,如果确实需要,您可以将列表转换为数组:

s1 = categories.toArray(new String[0]);

如果您对我为什么传递零长度数组感到困惑,请进一步研究:What to pass to the Arrays instance method toArray(T[] a) method?

其他需要注意的事项:

  • Java 区分大小写,S1s1 不同,请参阅您的 %! 部分。
  • 不是s1[]=,而是简单的s1= - 见How to initialize an array in Java?
  • 创建数组时需要指定数组的大小...即= new String[10] vs new String []
  • 我相信你的 仍然需要以分号结尾 (;)。

不管怎样,经过所有这些更正,它应该是这样的:

<%! String [] s1 = new String[0]; %>

我们本可以指定 null,但我不知道其余代码是否可以。这似乎只是目前最谨慎的做法。

现在,由于您使用的是ListArrayList,因此您需要import sections

<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>

如果你真的想对这些类别做点什么,你会想写类似这样的东西:

<% for (String category:categories) { %>
<p><%=category%></p>
<% } %>

请注意,我什至没有使用s1S1(无论您如何称呼本机数组),而是直接使用了categories List(因此确实不需要进行转换)。

请注意,我为您提供的解决方案有很多话要说,但我认为它是直接回答您问题的最简单的解决方案。

【讨论】:

    猜你喜欢
    • 2014-12-12
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-25
    • 2014-09-29
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多