今天girlfriend到公司交作业(还是培训期),她们的pm让她们在数据读取的使用FOR循环(如例test1),问之,为啥,说pm说了,这样好,还拿了一本pm给的Effective Java,说看了就明白,废话不多说,看之,原来就这样一条,如果在循环体外不需要继续使用的变量建议使用FOR循环,并且在for的第一部分初始化,这样一来循环结束以后就会自动回收,但是大家仔细思考一下,这地方能利用这条原则??,RESULTSET import java.sql.Connection; import jp.gibraltar.util.DBUtil; /** public static void main(String[] args) { /* /* public final void testExecuteCheckInput() { void test1() { Connection conn = DBUtil.getConnection(); try { vs.add(rs.getString(1)); } catch (SQLException e) { } void test2() { Connection conn = DBUtil.getConnection(); try { } stmt.close(); }
是跟着statement走的,当你关闭statement,resultset会被关闭,使你使用FOR循环没有任何好处,相反,WHILE要更快,使用for是弄巧成拙.例子如下,大家也看到while要比for快将近3倍,记录为1000条左右.写这个例子,希望大家不要犯类似的错.....
package jp.gibraltar.bnas.branch.aclearcase/" target="_blank" >ccountclose.closecheck;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import junit.framework.TestCase;
* @author sfluo
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class CloseCheckInputActionTest extends TestCase {
junit.textui.TestRunner.run(CloseCheckInputActionTest.class);
}
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
CloseCheckInputActionTest test = new CloseCheckInputActionTest();
System.out.println(System.currentTimeMillis());
test.test1();
System.out.println(System.currentTimeMillis());
test.test2();
System.out.println(System.currentTimeMillis());
}
Vector vs = new Vector();
Statement stmt = conn.createStatement();
for (ResultSet rs = stmt
.executeQuery("select * from accesslog_bnas "); rs.next();) {
stmt.close();
conn.close();
}
// TODO Auto-generated catch block
e.printStackTrace();
}
Vector vs = new Vector();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from accesslog_bnas ");
while (rs.next()) {
vs.add(rs.getString(1));
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
print
1100141162919
1100141174035
1100141178942