需求:
1.通过键盘录入用户名和密码
2.判断用户是否登录成功
select * from user where username="" and password=""; 如果这个sql有查询结果 则成功 反之 则失败
步骤:
1.创建数据表user
sql语句
![复制代码](https://common.cnblogs.com/images/copycode.gif)
CREATE TABLE user( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(32), password VARCHAR(32) ); INSERT INTO user VALUES(null,"zhangsan","123"); INSERT INTO user VALUES(null,"lisi","456");
![复制代码](https://common.cnblogs.com/images/copycode.gif)
测试类
![复制代码](https://common.cnblogs.com/images/copycode.gif)
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 JDBCDemo07().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; } // 连接数据库判断是否登录成功 Connection conn = null; Statement stmt = null; // 1.获取连接 try { conn = JDBCUtil.getConnection(); // 2.定义sql String sql = "select * from user where username='" + username + "' and password='" + password + "'"; // 3.获取执行sql的对象 stmt = conn.createStatement(); // 4.执行查询 ResultSet rs = stmt.executeQuery(sql); // 判断 return rs.next(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtil.close(stmt, conn); } return false; }
![复制代码](https://common.cnblogs.com/images/copycode.gif)
运行结果