JDBC PreparedStatement解决SQL注入问题

PreparedStatement解决SQL注入问题

package com.atguigu2.statement.crud;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.junit.Test;

import com.atguigu3.util.JDBCUtils;

/*
 * 演示PreparedStatement替换Statement解决SQL注入问题
 * 除了解决Statement的拼串,sql问题之外,PreparedStatement还有哪些好处呢
 * 1、PreparedStatement操作Blob的数据,而Statement做不到
 * 2、PreparedStatement可是实现更高效的批量操作
 * 
 */
public class PreparedStatementTest2 {
	@Test
	public void testLogin() {
		Scanner scanner=new Scanner(System.in);	
		System.out.println("请输入用户名:");
		String user=scanner.nextLine();
		System.out.println("请输入密码:");
		String password=scanner.nextLine();
		String sql="SELECT user,password FROM user_table WHERE user = ? and password = ?";
		User returnUser=getInstance(User.class,sql,user,password);
		if (returnUser!=null) {
			System.out.println("登陆成功");
		}else {
			System.out.println("用户名不存在或密码错误");
		}
	}
	
	
	public <T> T getInstance(Class<T> clazz, String sql,Object...args){
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			conn = JDBCUtils.getConnectio();
			
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i+1,args[i]);
			}
			
			rs = ps.executeQuery();
			//获取结果集的元数据 
			ResultSetMetaData rsmd = rs.getMetaData();
			//通过ResultSetMetaData获取结果集中的列数
			int columnCount = rsmd.getColumnCount();
			
			if(rs.next()) {
				T t=clazz.newInstance();
				//处理结果集一行数据中的每一个列:给T对象指定的属性赋值
				for (int i = 0; i < columnCount; i++) {
					//获取列值
					Object columValue = rs.getObject(i+1);
					
					//获取每个列的列名
					String columnLable = rsmd.getColumnLabel(i+1);
					
					//给t对象指定的columnName属性,赋值为columValue,通过反射
					Field field=clazz.getDeclaredField(columnLable);
					field.setAccessible(true);
					field.set(t, columValue);
				
			}
			return t;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.closeResource(conn, ps,rs);

		}
		return null;
	}
	
}

posted @ 2020-06-03 18:31  秋弦  阅读(266)  评论(0编辑  收藏  举报