【问题标题】:Trying to store information from database into array?试图将数据库中的信息存储到数组中?
【发布时间】:2021-02-17 13:55:43
【问题描述】:

所以我目前正试图弄清楚如何将我的数据从 SQlite 数据库存储到一个数组中,以便我可以在其他地方使用这个数组来管理它的数据。我正在尝试从名为 ProjectInfo 的表中读取所有数据,在此表中,我使用 projectName 列使用 while 循环检索所有数据。

   public static String [] readAllData () {
        //Connecting to database
        Connection con = DbConnection.connect();
        //Preparing statement
        PreparedStatement ps = null;
        //result set declaration
        ResultSet rs = null;

        //tableData String array
        String tableData [] = new String[300];

            try {
                //Database initialization
                String sql = "SELECT * FROM ProjectInfo";
                ps = con.prepareStatement(sql);
                rs = ps.executeQuery();

                //counter initialization
                int counter = 0;

                while (rs.next()) {
                    //for each iteration store the data into variable a from column projectName
                    String a = rs.getString("projectName");
                    //print out each element to see what is happening
                    System.out.println("a = " + a);
                    //increment counter
                    counter++;
                    
                    //for each increment, store a element from projectName
                    tableData[counter] = a;
                    
                    //testing extra stuff
                    //String b = rs.getString("teamName");
                    //String c = rs.getString("teamLocation");
                    //String d = rs.getString("supportTeamLocation");
                }
                //other catch exceptions
            } catch (SQLException e) {
                System.out.println(e.toString());
            } finally {
                try {
                    rs.close();
                    ps.close();
                    con.close();
                } catch (SQLException e){
                    System.out.println(e.toString());
                }
            }

        System.out.println(tableData);
            //return all the data that has been stored into this array 
            return tableData;

        }

当我运行我的代码时,我遇到了以下问题

[Ljava.lang.String;@4c402120

不知道从这里去哪里?

【问题讨论】:

    标签: java arrays sqlite android-sqlite


    【解决方案1】:

    如果要打印数组的项,必须使用Arrays.toString(),它返回一个由逗号分隔的数组所有项组成的字符串:

    System.out.println(Arrays.toString(tableData));
    

    你必须使用这个导入:

    import java.util.Arrays;
    

    另外,移动线:

    counter++;
    

    在这一行之后:

    tableData[counter] = a;
    

    因为数组的索引是基于0

    【讨论】:

      猜你喜欢
      • 2012-08-03
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 2018-10-15
      • 2010-12-05
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多