使用jdbc执行SQL实现登录查询2-避免SQL注入版
生活随笔
收集整理的這篇文章主要介紹了
使用jdbc执行SQL实现登录查询2-避免SQL注入版
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
配置文件及工具類參考1
package com.jdsc;import javax.rmi.CORBA.Util; import java.sql.*; import java.util.Scanner;/*** @author Alina* @date 2022年02月06日 12:13 上午* 判斷用戶登錄是否成功* 使用prepareStatement 執行SQL謹防SQL注入*/ public class jdbcDemo7 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.println("請輸入姓名:");String name = sc.nextLine();System.out.println("請輸入密碼:");String password = sc.nextLine();boolean login = new jdbcDemo7().login(name,password);if(login){System.out.println("登錄成功");}else {System.out.println("失敗");}}public boolean login(String name,String password){if(name==null||password==null){return false;}Connection conn = null;//返回值值是PreparedStatement類型PreparedStatement pstmt = null;ResultSet res = null;try {//1.連接數據庫conn = Utils.JDBCUtils.getconnection(); // 2.定義SQL select * from user where name = ''and password = ''; // String sql = "select * from user where name = '"+name+"'and password = '"+password+"'"; // 重新定義SQLString sql = "select * from user where name = ? and password = ?"; // 3.獲取執行SQL的對象 // stml = conn.createStatement(); // 使用prepareStatement 執行SQL謹防SQL注入pstmt = conn.prepareStatement(sql);//使用PreparedStatement serString()方法傳入sql語句,第一個值是位置,第二個是參數pstmt.setString(1,name);pstmt.setString(2,password);res = pstmt.executeQuery();// res = stml.executeQuery(sql);return res.next();} catch (SQLException throwables) {throwables.printStackTrace();}finally {//修改第二個參數Utils.JDBCUtils.close(res,pstmt,conn);}return false;} }總結
以上是生活随笔為你收集整理的使用jdbc执行SQL实现登录查询2-避免SQL注入版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python写机器人程序_用Python
- 下一篇: Redis客户端工具安装