PreparedStatement防注入demo

PreparedStatement有效防止注入的简单示例(源码在后面):
(statement实现简单注入在上一篇博客)
程序截图:
图一 登录成功
图一
图二 登录失败
图二
图三 SQL简单注入失效
图三
图四 数据库表截图
图四

程序源码:

package sqlzhuru;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class preparedstatement {
	public static void query() {
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try {
			String URL="jdbc:mysql://localhost:3306/xuexi";
			String name="root";
			String pwd="YES";
			Class.forName("com.mysql.jdbc.Driver");
			conn=DriverManager.getConnection(URL, name, pwd);
			String sql="select count(*) from login where uname=? and upwd=?";
			Scanner input =new Scanner(System.in);
			System.out.println("请输入用户名:");
			String uname=input.nextLine();
			System.out.println("请输入密码:");
			String upwd=input.nextLine();
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1, uname);
			pstmt.setString(2, upwd);
			rs=pstmt.executeQuery();
			int count=-1;
			if(rs.next()) {
				count=rs.getInt(1);
			}
			if(count>0) {
				System.out.println("登录成功!");
			}else {
				System.out.println("登陆失败!");
			}
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}
		finally {
			if(rs!=null) {
				try {rs.close();
			}catch(SQLException e) {
				e.printStackTrace();
			}
		    }
			if(pstmt!=null) {
				try {
					pstmt.close();
				}catch(SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn!=null) {
				try {
					pstmt.close();
				}catch(SQLException e) {
					e.printStackTrace();
				}
			}
	}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
         query();
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_43752257/article/details/107725944
今日推荐