java程序員面試必答題--數據庫
這道題我在好多個公司都考了,現在總結下來
?
寫一種數據庫操作
?
最通用的答案是使用數據源的
?
1、完整的,基于struts框架的
?
//取得當前模型 struts
ServletContext context = getServlet().getServletContext();
//指定配置文件???????
ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig(request, context);
?
//取得配置文件中指定的數據源
DataSource dataSource = (DataSource) context.getAttribute(key + moduleConfig.getPrefix());
?
//取得數據庫連接
Connection conn = dataSource.getConnection();
?
//準備sql操作
ps = conn.prepareStatement(sql);
?
//sql問中參數綁定
statement.setString(綁定參數位置, 所需綁定的參數);
?
//執行sql
rs = ps.executeQuery();
?
//結果rs保存
??while (rs.next()) {
???rs.getInt("aa");
???rs.getString("bb");
??}
?
2、簡單的
//取得數據庫連接
Connection conn = dataSource.getConnection();
?
//準備sql操作
ps = conn.prepareStatement(sql);
?
//執行sql
rs = ps.executeQuery();
?
//結果rs保存
??while (rs.next()) {
???rs.getInt("aa");
???rs.getString("bb");
??}
posted on 2006-03-25 18:11
MEYE 閱讀(391)
評論(0) 編輯 收藏