您的位置:首页 > 数据库

补10.17Servlet 登录注册案例 连接数据库

2011-10-30 22:04 543 查看
package cn.csdn.web.dao;

import java.io.File;

import java.io.FileInputStream;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import cn.csdn.web.domain.User;

import cn.csdn.web.util.JdbcUtil;

public class UserDaoImpl implements UserDao {

/* 封装数据库操作属性 */

private Connection conn;

private PreparedStatement pstmt;

private ResultSet rs;

/* 登录功能 */

public boolean checkUser(String name, String pass) {

/* 第一步:声明返回值变量 */

boolean flag = false;

/* 第二步:获取连接对象 */

conn = JdbcUtil.getConn();

/* 第三步:声明sql语句 */

String sql = "select id,name,pass,sex,age,rdate,birth,salary,photo from user where name=? and pass=?";

try {

/* 第四步:根据sql语句创建预处理对象 */

pstmt = conn.prepareStatement(sql);

/* 第五步:为占位符赋值 */

int index = 1;

pstmt.setObject(index++, name);

pstmt.setObject(index++, pass);

/* 第六步:执行查询 */

rs = pstmt.executeQuery();

/* 第七步:判断 */

if (rs.next()) {

flag = true;

}

/* 第八步:释放资源 */

JdbcUtil.release(rs, pstmt);

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

/* 修改返回值变量 */

return flag;

}

/* 注册功能 */

public boolean insert(User entity) {

/* 第一步:声明返回值变量 */

boolean flag = false;

/* 第二步:获取连接对象 */

conn = JdbcUtil.getConn();

/* 第三步:声明sql语句 */

String sql = "insert into user(name,pass,sex,age,rdate,birth,salary) values(?,?,?,?,?,?,?)";

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.getRdate());

pstmt.setObject(index++, entity.getBirth());

pstmt.setObject(index++, entity.getSalary());

/* 第六步:执行更新 */

int i = pstmt.executeUpdate();

/* 第七步:执行判断 */

if (i > 0) {

flag = true;

}

/* 第八步:释放资源 */

JdbcUtil.release(rs, pstmt);

} catch (SQLException e) {

e.printStackTrace();

}

/* 修改返回值变量 */

return flag;

}

/*添加头像*/

public boolean updatePhoto(User entity,File file) {

/*第一步:声明返回值变量*/

boolean flag = false;

/*第二步:获取连接对象*/

conn = JdbcUtil.getConn();

/*第三步:定义sql语句*/

String sql="update user set photo=? where id=?";

try {

/*第四步:根据预处理的sql语句创建预处理对象*/

pstmt = conn.prepareStatement(sql);

/*第五步:为占位符 赋值*/

int index=1;

/*根据file文件创建输入流 */

FileInputStream is = new FileInputStream(file);

/*将指定参数设置为给定输入流,该输入流将具有给定字节数*/

pstmt.setBinaryStream(index++, is,file.length());

pstmt.setObject(index++, entity.getId());

/*第六步:执行更新*/

int i = pstmt.executeUpdate();

/*第七步:判断*/

if(i>0){

flag=true;

}

/*第八步:释放资源*/

JdbcUtil.release(rs, pstmt);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

/*修改返回值变量*/

return flag;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: