BaseDao中直接跳过向服务器发送SQL语句的这几行 都有哪些可能

YafengLiang 2015-12-13 05:26:20
package com.bdqn.shop.tools;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;


public class BaseDao {
protected Connection connection;
private ResultSet rs;

protected Connection getConnection(){
try {
Context cxt = new InitialContext();
DataSource ds = (DataSource) cxt.lookup("java:comp/env/jdbc/shop");
//获取连接
connection= ds.getConnection();
} catch (Exception e) {

}
return this.connection;
}
/**
* 执行select语句
* @param sql select语句
* @param params 参数的值
* @return
*/
public ResultSet getResult(String sql,Object[] params){
try {
this.getConnection();
//连接创建PreparedStatement对象
PreparedStatement smt = connection.prepareStatement(sql);
if(params!=null){
for (int i = 0; i <params.length; i++) {
smt.setObject(i+1, params[i]);
}
}
//向服务器发送SQL语句,并返回查询的结果集
this.rs = smt.executeQuery();
} catch (Exception e) {
// TODO: handle exception
}
return rs;
}
/**
* 执行insert update delete语句
* @param insert update delete语句
* @param params 参数
* @return 是否执行成功
*/
public boolean saveResult(String sql,Object[] params){
boolean flag=false;
try {
this.getConnection();
//连接创建PreparedStatement对象
PreparedStatement smt = connection.prepareStatement(sql);
if(params!=null){
for (int i = 0; i <params.length; i++) {
smt.setObject(i+1, params[i]);
}
}
//向服务器发送SQL语句,返回受影响的行数
int row = smt.executeUpdate();
if(row==1){
flag=true;
}
} catch (Exception e) {
e.printStackTrace();
flag=false;
}finally{
this.closeResource();
}
return flag;
}
public void closeResource(){
try {
if (this.rs != null) {
rs.close();
}
if(this.connection!=null){
connection.close();
}
} catch (Exception e) {
// TODO: handle exception
}
}

}
...全文
143 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
街头小贩 2015-12-14
  • 打赏
  • 举报
回复
不明白你想问什么?你这是一个自已封装的db类?你这种参数类型不安全,效率也不高!为什么不用commons dbUtils?这个效率比jdbc原始代码不分上下

2,129

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧