用jdbc操作数据库的简单例子(二)

2014-11-24 08:59:11 · 作者: · 浏览: 5
import cn.csdn.web.Util.JdbcUtil;
import cn.csdn.web.domain.Users;
public class UsersDaoImpl implements UsersDao {
//封装数据库对象
private static Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
//增
public boolean insert(Users entity) {
//声明返回值变量
boolean flag = false;
//获取连接对象
conn = JdbcUtil.getConn();
//定义sql语句
String sql = "insert into users(id,name,pass,sex,age) values( , , , , )";
try {
//根据sql语句创建预处理对象
pstmt = conn.prepareStatement(sql);
//为占位符赋值
int index = 1;
pstmt.setObject(index++, entity.getId());
pstmt.setObject(index++, entity.getName());
pstmt.setObject(index++, entity.getPass());
pstmt.setObject(index++, entity.getSex());
pstmt.setObject(index++, entity.getAge());
//执行更新
int i = pstmt.executeUpdate();
if(i>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//释放资源
JdbcUtil.release(rs, pstmt);
return flag;
}
//删
public boolean deleteById(Integer id) {
//声明返回值变量
boolean flag = false;
//获取连接对象
conn = JdbcUtil.getConn();
//定义sql语句
String sql = "delete from users where id= ";
try {
//根据sql语句创建预处理对象
pstmt = conn.prepareStatement(sql);
//为占位符赋值
int index = 1;
pstmt.setObject(index++, id);
//执行更新
int i = pstmt.executeUpdate();
if(i>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//释放资源
JdbcUtil.release(rs, pstmt);
return flag;
}
//改
public boolean updateById(Users entity) {
//声明返回值变量
boolean flag = false;
//获取连接对象
conn = JdbcUtil.getConn();
//定义sql语句
String sql = "update users set name= ,pass= ,sex= ,age= where id= ";
try {
//根据sql语句创建预处理对象
pstmt = conn.prepareStatement(sql);
//为占位符赋值
int index = 1;
pstmt.setObject(index++, entity.getName());
pstmt.setObject(index++, entity.getPass());
pstmt.setObject(index++, entity.getSex());
pstmt.setObject(index++, entity.getAge());
pstmt.setObject(index++, entity.getId());
//执行更新
int i = pstmt.executeUpdate();
if(i>0){
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//释放资源
JdbcUtil.release(rs, pstmt);
return flag;
}
//查
public Users findById(Integer id) {
//声明返回值变量
Users entity = new Users();
//获取连接对象
conn = JdbcUtil.getConn();
//定义sql语句
String sql = "select * from users where id= ";
try {
//根据sql语句创建预处理对象
pstmt = conn.prepareStatement(sql);
//为占位符赋值
int index = 1;
pstmt.setObject(index++, id);
//执行更新
rs = pstmt.executeQuery();
if(rs.next()){
entity.setId(rs.getInt("id"));
entity.setName(rs.getString("name"));
entity.setPass(rs.getString("pass"));
entity.setSex(rs.getString("sex"));
entity.setAge(rs.getInt("age"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//释放资源
JdbcUtil.release(rs, pstmt);
return entity;
}
}
junit测试
package cn.csdn.web.junit;
import org.junit.Test;
import cn.csdn.web.dao.UsersDa