爪哇 - 中储存select语句的ArrayList中的结果是好还是坏的做法? [英] Java - Is storing the result of select statement in arraylist is good or bad approach?

查看:114
本文介绍了爪哇 - 中储存select语句的ArrayList中的结果是好还是坏的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习在Java的SQL Server 2008。所以我在想,如果使用这种方法是一个很好的或不?我实现了一个通用的ArrayList的方法,它将从数据库中获取的值。

I am just starting to learn with SQL server 2008 in java. So I was wondering if using this approach is a good one or not? I implemented a generic arraylist method which will get the values from the database.

public ArrayList<String> get(){
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    ArrayList<String> a = new ArrayList<String>();
    try {

        // Register JDBC driver
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        conn = DriverManager.getConnection("jdbc:sqlserver://localhost; database = Sample; Integratedsecurity = true");
        String  sql = "Select * from products";
        stmt = conn.prepareStatement(sql);
        // Extract all the records to see the updated records
         rs  = stmt.executeQuery();
        while (rs.next()) {
            // Retrieve data by column name in your database
          a.add(rs.getString("ProductName"));

        }
        rs.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    return a;
}

请问这个是好还是不好?然后在显示它。

Will this one is good or not? Then in displaying it..

ArrayList<String> a = new ArrayList<String>();
        String productName = !request.getParameter("productName").isEmpty() ? request.getParameter("productName") : "Empty";
        d.addProduct(productName);
        a = d.get();

        Iterator<String> it = a.iterator();

        while(it.hasNext()){%>
            <% String baba = (String)it.next(); %>
            <p>Product:  <%= baba %></p>
        <%} %>

我想知道是否有任何好的的建立做这一点,更容易理解?任何帮助/建议将是AP preciate!谢谢你。

I am wondering if there's any good set-up in doing this and much more easy to understand? Any help/suggestions would be appreciate! Thank you.

推荐答案

这是罚款。

这种方法效果很好,即使你有更大的结果集行。然后,您可以把每一行成某种类型的对象,并添加到数组列表。

The approach works well even when you have larger result set rows. You would then turn each row into an object of some kind and add that to the Array list.

凡可能无法正常工作这么好是当你不能所有的行检索由于内存的限制,但你仍然会添加要回到这样一个集合的人。

Where it may not work so well is when you can not retrieve all of the rows due to memory constraints but you would still add the ones you want to return to such a collection.

这篇关于爪哇 - 中储存select语句的ArrayList中的结果是好还是坏的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆