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

 

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;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值