sql注入与防止sql注入

数据库中的数据

sql代码

package com.zjw.jdbc2;

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

/*
 * sql注入
 */
public class SqlInject
{
	public static void main(String[] args)
	{
		try
		{
			//加载驱动
			Class.forName("com.mysql.cj.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/aaa?useSSL=false&serverTimezone=UTC";
			String user = "root" ;
			String password = "123456";
			
			//获取连接
			Connection con = DriverManager.getConnection(url, user, password);
			Statement stat = con.createStatement();
			
			//输入用户名和密码
			@SuppressWarnings("resource")
			Scanner sc = new Scanner(System.in);
			String inName = sc.nextLine();
			String inPass = sc.nextLine();
			//查询数据库
			String sql = "SELECT * FROM category WHERE sid = '"+inName+"' AND sname = '"+inPass+"';";
			System.out.println(sql);
			//结果处理
			ResultSet res = stat.executeQuery(sql);
			while(res.next())
			{
				String sid = res.getString("sid");
				String sname = res.getString("sname");
				System.out.println(sid+"  "+sname);
			}
			//释放资源
			res.close();
			stat.close();
			con.close();
		} catch (ClassNotFoundException | SQLException e)
		{
			e.printStackTrace();
		}
		
	}
}

结果:

 防止sql注入代码:

package com.zjw.jdbc2;

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

/*
 * 防止sql注入
 */
public class SqlInject2
{
	public static void main(String[] args)
	{
		try
		{
			//加载驱动
			Class.forName("com.mysql.cj.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/aaa?useSSL=false&serverTimezone=UTC";
			String user = "root" ;
			String password = "123456";
			
			//获取连接
			Connection con = DriverManager.getConnection(url, user, password);
			
			//输入用户名和密码
			@SuppressWarnings("resource")
			Scanner sc = new Scanner(System.in);
			String inName = sc.nextLine();
			String inPass = sc.nextLine();
			
			//查询数据库
			String sql = "SELECT * FROM category WHERE sid = ? AND sname = ? ;";
			PreparedStatement pst = con.prepareStatement(sql);//PreparedStatement为Satetment的子接口
			pst.setString(1, inName);//设置参数
			pst.setString(2, inPass);
			
			//结果处理
			ResultSet res = pst.executeQuery();//调用方法不用加sql
			while(res.next())
			{
				String sid = res.getString("sid");
				String sname = res.getString("sname");
				System.out.println(sid+"  "+sname);
			}
			//释放资源
			res.close();
			pst.close();
			con.close();
		} catch (ClassNotFoundException | SQLException e)
		{
			e.printStackTrace();
		}
		
	}
}

结果:

正常输入数据

异常输入数据

posted @ 2018-10-19 13:47  雨中遐想  阅读(5)  评论(0编辑  收藏  举报  来源