Java SQL结果集检索顺序不正确

Java SQL结果集检索顺序不正确

问题描述:

我的表中有以下三行说tb1

Hi I have the following three row in my table say tb1

key   time   id   rowid
X     11:40  1      1
Y     4:50   1      2
Z     6:48   1      2 

现在,我正在使用JDBC来获取记录并遍历结果集,如下所示:

Now I am using JDBC to get records and iterating over resultset as shown below:

rs = statement.executeQuery("select * from tb1")
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
while(rs.next())
{
   for(int i = 1; i <= cols ; i++)
   {
     System.out.println("col name " + md.getColumnName(i));
     System.out.println("col name " + rs.getObject(i));
   }

}

当我奇怪地执行以上代码时,它总是先打印第二行,然后再打印第一行,然后再打印第三行.简而言之,结果集的数据检索不正确.我不明白为什么?请指导.预先感谢.

When I execute the above code strangely it always prints second row first and then first row and then third row. In short resultset data retrieval is not in order. I dont understand why? Please guide. thanks in advance.

您尚未指定"order by"子句.通常,除非指定了"order by"子句,否则数据库不需要以任何顺序返回行.在您的select语句中添加order by子句.

You have not specified an "order by" clause. In general, databases are not required to return rows in any order unless an "order by" clause is specified. Add an order by clause to your select statement.