Java 将结果集存储到数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2699963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:59:29  来源:igfitidea点击:

Storing Result set into an array

javasqljdbcresultset

提问by OVERTONE

i know this should be simpel and im probably staring straight at the problem but once again im stuck and need the help of the code gurus.

我知道这应该很简单,我可能直接盯着问题看,但我又一次卡住了,需要代码大师的帮助。

im trying too take one row from a column in jdbc, and put them in an array.

我也尝试从 jdbc 的一列中取出一行,并将它们放入一个数组中。

i do this as follows:

我这样做如下:

public void fillContactList()
       {
           createConnection();
           try
           {
               Statement stmt = conn.createStatement();
               ResultSet namesList = stmt.executeQuery("SELECT name FROM Users");
               try
               {
                   while (namesList.next())
                   {
                       contactListNames[1] = namesList.getString(1);
                       System.out.println("" + contactListNames[1]);
                   }   
               }
               catch(SQLException q)
               {

               }
               conn.commit();
               stmt.close();
               conn.close();
           }
           catch(SQLException e)
           {

           }

creatConnection is an already defined method that does what it obviously does. i creat my result set while theres another one, i store the string of that column into an array. then print it out for good measure. too make sure its there.

creatConnection 是一个已经定义的方法,它可以完成它显然所做的事情。我创建了我的结果集,而另一个结果集,我将该列的字符串存储到一个数组中。然后打印出来以备不时之需。也确保它在那里。

the problem is that its storing the entire column into contactListNames[1]

问题是它将整个列存储到 contactListNames[1]

i wanted to make it store column1 row 1 into [1]

我想让它存储 column1 行 1 到 [1]

then column 1 row 2 into [2]

然后第 1 列第 2 行变成 [2]

i know i could do this with a loop. but i dont know too take only one row at a time from a single column. any ideas?

我知道我可以用循环来做到这一点。但我不知道从一列中一次只取一行。有任何想法吗?

p.s ive read the api, i jsut cant see anything that fits.

ps我读过api,我只是看不到任何合适的东西。

采纳答案by Kevin Brock

You should use an ArrayListwhich provides all the logic to automatically extend the array.

您应该使用ArrayList提供所有逻辑来自动扩展数组的 。

List rowValues = new ArrayList();
while (namesList.next()) {
    rowValues.add(namesList.getString(1));
}   
// You can then put this back into an array if necessary
contactListNames = (String[]) rowValues.toArray(new String[rowValues.size()]);

回答by Binil Thomas

Did you mean something like:

你的意思是这样的:

int i = 0;
ResultSet rs = stmt.executeQuery("select name from users");
while (rs.next()) {
    String name = rs.getString("name");
    names[i++] = name;
}