package cn.itcast.jdbc;import cn.itcast.util.JDBCUtils;import java.sql.*;import java.util.Properties;import java.util.Scanner;/** * @author newcityman * @date 2019/8/15 - 21:28 * 1、 通过键盘录入用户名和密码 * 2、 判断用户是否登录成功 */public class JDBCDemo08 {public static void main(String[] args) { System.out.println("请输入用户名:"); Scanner sc = new Scanner(System.in); String username = sc.next(); System.out.println("请输入密码"); String password = sc.next(); /* boolean flag = new JDBCDemo08().login(username, password); if (flag) { System.out.println("登录成功"); } else { System.out.println("用户名或密码错误,请联系系统管理员"); }*/ boolean f = new JDBCDemo08().login2(username, password); if (f) { System.out.println("登录成功"); } else { System.out.println("用户名或密码错误,请联系系统管理员"); } }/* *登录方法 * * */ public boolean login(String username, String password) { Connection conn = null; Statement stmt = null; ResultSet rs = null; if (username == null || password == null) {return false; }try {// 1、 获取连接 conn = JDBCUtils.getConnection();// 2、 定义sql String sql = "select * from user where name='" + username + "'and password='" + password + "'"; System.out.println(sql);// 3、 获取执行sql的对象 stmt = conn.createStatement();// 4、执行查询 rs = stmt.executeQuery(sql);// 5、判断 /*if (rs.next()) { System.out.println("登录成功"); return true; } else { System.out.println("用户名或密码错误,请重新输入"); return false; }*/ return rs.next(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.close(rs, stmt, conn); }return false; }/* *登录方法2:防止sql注入 * * */ public boolean login2(String username, String password) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; if (username == null || password == null) {return false; }try {// 1、 获取连接 conn = JDBCUtils.getConnection();// 2、 定义sql String sql = "select * from user where name=? and password=?";// 3、 获取执行sql的对象 stmt = conn.prepareStatement(sql); stmt.setString(1,username); stmt.setString(2,password);// 4、执行查询 rs = stmt.executeQuery();// 5、判断 /*if (rs.next()) { System.out.println("登录成功"); return true; } else { System.out.println("用户名或密码错误,请重新输入"); return false; }*/ return rs.next(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.close(rs, stmt, conn); }return false; }}
转载于:https://www.cnblogs.com/newcityboy/p/11360933.html
转载请注明原文地址: https://mac.8miu.com/read-54779.html