从MySQL在Java中检索记录Retrieving records from MySQL in Java

- 此内容更新于:2014-12-30
主题:

原文:

I'm building an application in Java to retrieve data from MySQL database. After executing a query I get a ResultSet and do the following to extract records:

while (rs.next())
        {
            for (int column = 1; column <= rm.getColumnCount(); column++) {
                row.add(rs.getObject(column));
            }
            result.add(row.toString());
            row.clear();
        }

where rs = ResultSet and rm = ResultSetMetaData

The problem is that I have to do result.add(row.toString()); rather than just result.add(row); (with which I'd like to create a two-dimensional ArrayList). Otherwise I get empty results.

I have tried putting row.clear(); at the beginning, before the for loop, but that results in all my results being filled with multiple instances of the last record. Just like row was not added to the result until the very end, when it's equal to the last record. Do I need to "commit" the ArrayList row before adding it as an elemt to another ArrayList? If so, how? Also, out of curiosity, why is .toString() working differently?

解决方案:
通过添加row.toString(),你创建一个新的字符串对象添加到结果。 另一方面,通过添加行,你将同一个对象添加到结果,因此,每次row.clear(),它在结果空的所有行。 你应该做的是创建一个新行对象在for循环之前,不要做row.clear()。下面是一个例子。
原文:

By adding row.toString(), you're creating a new String object to add into result.

On the other hand, by adding row, you're adding the same object into result, therefore, each time row.clear() is called, it empty all the rows in result.

What you should do is to create a new row object before the for loop, and don't do row.clear(). Following is an example.

while (rs.next())
        {
			row = new ArrayList();

            for (int column = 1; column <= rm.getColumnCount(); column++) {
                row.add(rs.getObject(column));
            }

			result.add(row);
        }
Maciek Gryka的回复:好吧,基本上result.add(行)就像“经过reference",不是复制的对象,只是提供一个参考吗?谢谢,这解决了我的问题:)

(原文:OK, so basically result.add(row) works like "pass by reference", not copying the object, but just providing a reference to it? Thanks, that solved my problem :))