练习:
需求:
- 通过键盘录入用户名和密码
- 判断用户是否登录成功,如果登录成功提示登录成功
步骤:
创建一个数据库表users
CREATE TABLE users1(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32),
PASSWORD VARCHAR(32)
)
SELECT * FROM users1;
INSERT INTO users1 VALUES(NULL,'张三','123'),
(NULL,'李四','456');
然后从键盘接受两条数据分别为 username 和 password
然后运用以下sql语句在数据库中进行查找
sql * from users1 where username='xxx' and password='xxx';
若存在查询结果则说明该用户存在且密码正确
代码如下:
package zr.jdbc;
import JDBCUtils.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
* 练习:
* 需求:
* 通过键盘录入用户名和密码
* 判断用户是否登录成功,如果登录成功提示登录成功
*/
public class jdbcDemo2 {
public static void main(String[] args) {
//1.键盘录入
Scanner sc=new Scanner(System.in);
System.out.println("请输入用户名:");
String username=sc.nextLine();
System.out.println("请输入密码:");
String password=sc.nextLine();
//2.调用方法
boolean flag=new jdbcDemo2().login(username,password);
//3.判断结果,输出不同语句
if(flag){
System.out.println("登录成功!");
}else{
System.out.println("用户名或密码错误!");
}
}
/**
* 登录方法
*/
public boolean login(String username,String password){
if (username==null&&password==null){
return false;
}
//1.获取连接
Connection connection = JDBCUtils.getConnection();
String sql="select * from users1 where username= '"+username+"' and password= '"+ password+"' ";
Statement statement = null;
ResultSet rs=null;
try {
statement = connection.createStatement();
rs=statement.executeQuery(sql);
/*if (rs.next()){
return true;
}else {
return false;
}*/
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(rs,statement,connection);
}
return false;
}
}
这里面注意return rs.next();简化了程序,以后要注意类似的语句
还有String sql="select * from users1 where username= ' "+username+" ' and password= ' "+ password+" ' ";
注意这种sql语句的写法