问题遇到的现象和发生背景
idea java代码想通过JDBCUtils实现一个连接数据库模拟登陆的功能 结果输入正确的username和password也返回账号或密码错误
用代码块功能插入代码,请勿粘贴截图
package cn.itcast.jdbc;
import cn.itcast.domain.User;
import cn.itcast.utils.JDBCUtils;
import cn.itcast.utils.JDBCUtils_repeat;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class jdbcDemo08_login {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名:");
String username = sc.next();
System.out.println("请输入密码:");
String password = sc.next();
boolean flag = new jdbcDemo08_login().login(username, password);
if (flag == true ){
System.out.println("登陆成功!");
}else {
System.out.println("用户名或密码错误!");
}
}
public boolean login(String username,String password){
if (username == null || password ==null){
return false;
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
//连接数据库
try {
conn = JDBCUtils_repeat.getConnection();
/*String sql = "select * from user where username = ' "+username+"' and password = '"+password+"'";*/
String sql = "select * from user where username = ? and password = ? ";
ps = conn.prepareStatement(sql);
ps.setString(1,"username");
ps.setString(2,"password");
rs = ps.executeQuery();
return rs.next(); //如果有下一行,返回true
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils_repeat.close(rs,ps,conn);
}
return false;
}
}