DAO检测测试(二)

package com.itheima.login.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import com.itheima.login.domain.User;
import com.itheima.login.utils.JdbcUtils;

public class UserDao {

	//查询 单个 用户 , 这里 是dao的核心类, 封装了对数据源 的操作
	public User selectOne(User user) {
		
		
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			
//			获得链接
			conn = JdbcUtils.getConnection();
			
			// ? 表示占位符 
			String sql ="select * from users where username=? and password=?";
			
			//获得PreparedStatement对象
			stmt = conn.prepareStatement(sql);
			
			//替换占位符
			stmt.setString(1, user.getUsername());
			stmt.setString(2, user.getPassword());
			
			
			//拿到结果集
			rs = stmt.executeQuery();
			User loginUser = null;
			
			//解析结果集 
			if(rs.next()){
				
				loginUser = new User();
				int id = rs.getInt("id");
				String username = rs.getString("username");
				String password = rs.getString("password");
				String nickname = rs.getString("nickname");
				
				//封装登录用户的信息
				loginUser.setId(id);
				loginUser.setUsername(username);
				loginUser.setPassword(password);
				loginUser.setNickname(nickname);
				
			}
			
			return loginUser;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			
			
			JdbcUtils.release(rs, stmt, conn);
		}
		
	}
	//查询 单个 用户 , 这里 是dao的核心类, 封装了对数据源 的操作
	public User selectOne1(User user) {
		
		
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			
//			获得链接
			conn = JdbcUtils.getConnection();
			
			//获得statement对象
			stmt = conn.createStatement();
			
			// select * from users where username='' and password='';
			String sql = "select * from users where username='"+user.getUsername()+"' and password='"+user.getPassword()+"'";
			
			// select * from users where username='hehui' or '1'='1' and password='';
			//拿到结果集
			rs = stmt.executeQuery(sql);
			
			User loginUser = null;
			//解析结果集 
			if(rs.next()){
				
				loginUser = new User();
				int id = rs.getInt("id");
				String username = rs.getString("username");
				String password = rs.getString("password");
				String nickname = rs.getString("nickname");
				
				//封装登录用户的信息
				loginUser.setId(id);
				loginUser.setUsername(username);
				loginUser.setPassword(password);
				loginUser.setNickname(nickname);
				
			}
			
			return loginUser;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			
			
			JdbcUtils.release(rs, stmt, conn);
		}
		
	}

}

原文链接: DAO检测测试(二) 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-72.html )

发表评论

0则评论给“DAO检测测试(二)”