我對下面的課程有幾個問題。爲什麼sql連接在新線程中創建?
public class Test {
public void run() throws SQLException {
Connection conn = getConnection();
DSLContext create = DSL.using(conn, SQLDialect.MYSQL);
// query books for author named 'selena'
Result<Record2<Long, String>> result = create
.select(BOOK.ID, BOOK.TITLE).from(BOOK).join(BOOK_AUTHOR_REL)
.on(BOOK_AUTHOR_REL.BOOKID.equal(BOOK.ID)).join(AUTHOR)
.on(BOOK_AUTHOR_REL.AUTHORID.equal(AUTHOR.ID))
.where(AUTHOR.NAME.equal("selena"))
.orderBy(BOOK.TITLE.asc(), BOOK.ID.asc()).fetch();
result.forEach((r) -> {
System.out.println(String.format("%s (id: %s)",
r.getValue(BOOK.TITLE), r.getValue(BOOK.ID)));
});
conn.close();
System.exit(0);
}
public static void main(final String[] args) throws SQLException {
new Test().run();
}
private Connection getConnection() {
try {
Class.forName(System.getProperty("jdbc.driver")).newInstance();
return DriverManager.getConnection(System.getProperty("jdbc.url"),
System.getProperty("jdbc.user"),
System.getProperty("jdbc.password"));
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return null;
}
}
- 爲什麼新的連接得到一個新的線程產生的?爲什麼我們把它叫做
void run
而不是屬於類實例的其他方法? 爲什麼字符串參數
final
在這裏?public static void main(final String[] args) throws SQLException { new Test().run(); }
關閉連接後,爲什麼要撥打
System.exit()
?conn.close(); System.exit(0);
是什麼讓你覺得有多個線程參與? 'run'只是一種方法......對於第二個問題,這可能只是作者的首選風格。對於第三個問題......沒有真正的理由在這裏調用'System.exit(0)'......你爲什麼不問作者? – 2014-10-06 17:11:28