1. 程式人生 > 其它 >JDBC:createStatement(sql注入)與PrepareStatement(防止sql注入)程式案例程式碼優化

JDBC:createStatement(sql注入)與PrepareStatement(防止sql注入)程式案例程式碼優化

技術標籤:學習經驗jdbc

把程式中重複的程式碼寫為一個工具類。
在這裡插入圖片描述
createStatement

package cn.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.management.RuntimeErrorException;
import cn.IStudentDao.IStudentDao; import cn.jdbcUtils.jdbcUtils; import cn.student.Student; //實現介面 public class DaoDemo implements IStudentDao{ private static Connection connection ; private static Statement state; //實現 private static ResultSet update; @Override public List<Student> findAll
(Student student) { //建立一個集合儲存學生物件 List<Student> list = new ArrayList<Student>(); //sql語句命令 SELECT id,NAME,age FROM student_jdbc; String sql = "SELECT id,NAME,age FROM student_jdbc;"; try { //建立連線 connection = jdbcUtils.getConnection(); state = connection.createStatement
(); update = state.executeQuery(sql); while(update.next()) { Student stud = new Student(); stud.setId(update.getInt("id")); stud.setName(update.getString("name")); stud.setAge(update.getInt("age")); list.add(stud); } } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); }finally { jdbcUtils.closeAll(connection, state, update); } return list; } @Override public void save(Student student) { //sql語句命令 INSERT INTO student_jdbc(NAME,age) VALUES ("miemie2",19); //Student student = new Student(); String sql = "INSERT INTO student_jdbc(id,NAME,age) VALUES ('"+student.getId()+"','"+student.getName()+"',"+student.getAge()+")"; try { //建立連線 connection= jdbcUtils.getConnection(); //建立實現方法物件 Statement state = connection.createStatement(); //實現 int update = state.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); }finally { jdbcUtils.closeAll(connection, state, null); } } @Override public void update(Student student) { //sql語句命令 UPDATE student_jdbc SET age=20 WHERE id=1; String sql = "UPDATE student_jdbc SET age="+student.getAge()+",name='"+student.getName()+"' WHERE id="+student.getId()+";"; try { //建立連線 connection= jdbcUtils.getConnection(); //建立實現方法物件 Statement state = connection.createStatement(); //實現 int update = state.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); }finally { jdbcUtils.closeAll(connection, state, null); } } @Override public void delete(int id) { //sql語句命令 delete from student_jdbc where id=1; Student student = new Student(); String sql = "delete from student_jdbc where id="+id+""; try { //建立連線 connection= jdbcUtils.getConnection(); //建立實現方法物件 Statement state = connection.createStatement(); //實現 int update = state.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); }finally { jdbcUtils.closeAll(connection, state, null); } } @Override public Student findById(int id) { //sql語句命令 select id,name,age from student_jdbc where id=1; Student student = new Student(); String sql = "select name,age from student_jdbc where id="+id+";"; try { //建立連線 connection = jdbcUtils.getConnection(); //建立實現方法物件 Statement state = connection.createStatement(); //實現 ResultSet rs = state.executeQuery(sql); while(rs.next()){ student.setId(id); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); } //關閉 rs.close(); state.close(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } return student; } @Override public List<Student> findId(int index1, int index2) { //sql語句命令 select id,name,age from student_jdbc LIMIT 0,2; List<Student> list = new ArrayList<Student>(); //Student student = new Student(); String sql = "SELECT id,NAME,age FROM student_jdbc LIMIT "+index1+","+index2+";"; try { //建立連線 connection = jdbcUtils.getConnection(); //建立實現方法物件 Statement state = connection.createStatement(); //實現 ResultSet rs = state.executeQuery(sql); while(rs.next()){ Student student = new Student(); student.setId(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); list.add(student); } } catch (SQLException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } return list; } }
package cn.IStudentDao;


import java.util.List;

import cn.student.Student;

public interface IStudentDao {
	//查詢全部
	List<Student> findAll(Student student);
    //儲存
	void save(Student student);
	//更新
	void update(Student student);
	//刪除
	void delete(int id);
	//主鍵查詢
	Student findById(int id);
	//分頁查詢
	public List<Student> findId(int index1,int index2);
}

package cn.student;

public class Student {
   private int id;
   private String name;
   private int age;
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	this.age = age;
}
@Override
public String toString() {
	return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
   
}

package cn.jdbcUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.management.RuntimeErrorException;

public class jdbcUtils {
	private static Connection connection = null;
	private static Statement state = null;
	private static PreparedStatement prepstate = null;
	private static ResultSet rs = null;
    public static Connection getConnection() {
    	
    	//Connection connection = null;
		try {
    		//載入驅動類
			Class.forName("com.mysql.jdbc.Driver");
			//建立連線
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc", "root", "root");
		    //return connection;
    	} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return connection;	
    	
    }
    
    public static void closeAll(Connection connnection,Statement state,ResultSet rs) {
    	try {
    		if(rs!=null) {
    	       rs.close();
    	       rs = null;
    		}
    		if(state!=null) {
    			state.close();
    			state = null;
    		}
    		if(connection!=null) {
			   connection.close();
			   connection=null;
    		}		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
    	
    }
    
    //PreparedStatement優化(僅針對查詢操作)
    public static void setParameters(String sql,Object...parameters) {
    	try { 
			//建立連線
			connection = jdbcUtils.getConnection();
			//建立實現方法物件
			prepstate = connection.prepareStatement(sql);
			//設定sql語句中佔位符對應的值
			if(parameters!=null && parameters.length>0) {
				for(int i = 0;i<parameters.length;i++) {
					prepstate.setObject(i+1, parameters[i]);
				}
			}
			//執行命令
			int executeUpdate = prepstate.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}finally {
			jdbcUtils.closeAll(connection, prepstate, null);
		}
    }
}

package cn.test.jdbc;

import static org.junit.Assert.*;

import org.junit.Test;

import cn.IStudentDao.IStudentDao;
import cn.dao.DaoDemo;
import cn.dao.DaoDemoPrep;
import cn.student.Student;

public class TestDemo {
    private IStudentDao stud = new DaoDemo();
	//private IStudentDao stud = new DaoDemoPrep();
	@Test //
	public void testFindAll() {
		Student student = new Student();
		System.out.println(stud.findAll(student));
	}

	@Test
	public void testSave() {
		//模擬封裝
		Student student = new Student();
		student.setAge(18);
		student.setId(103);
		student.setName("jack");
		stud.save(student);
	}

	@Test //
	public void testUpdate() {
		Student student = new Student();
		student.setAge(18);
		student.setId(102);
		student.setName("Rose");
		stud.update(student);
	}

	@Test
	public void testDelete() {
		 stud.delete(103);
	}

	@Test 
	public void testFindById() {
		 System.out.println(stud.findById(6));
	}

	@Test
	public void testFindId() {
		System.out.println(stud.findId(0, 3));
	}

}

PrepareStatement

package cn.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.IStudentDao.IStudentDao;
import cn.jdbcUtils.jdbcUtils;
import cn.student.Student;

//實現介面
public class DaoDemoPrep implements IStudentDao{
	
	private static Connection connection;
	private  static PreparedStatement state;
	private static ResultSet update;

	@Override
	public List<Student> findAll(Student student) {
		//建立一個集合儲存學生物件
		List<Student> list = new ArrayList<Student>();
		//sql語句命令 SELECT id,NAME,age FROM student_jdbc;
		String sql = "SELECT id,NAME,age FROM student_jdbc;";
		try {
			//建立連線
			connection = jdbcUtils.getConnection();
			//建立實現方法物件
			state = connection.prepareStatement(sql);
			//實現
			update = state.executeQuery();
			while(update.next()) {
				Student stud = new Student();
				stud.setId(update.getInt("id"));
				stud.setName(update.getString("name"));
				stud.setAge(update.getInt("age"));
				list.add(stud);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException();
		}finally {
			jdbcUtils.closeAll(connection, state, update);
		}
		 return list;
	}

	@Override
	public void save(Student student) {
		//sql語句命令 INSERT INTO student_jdbc(NAME,age) VALUES ("miemie2",19);
		//Student student = new Student();
	  String sql = "INSERT INTO student_jdbc(id,NAME,age) VALUES (?,?,?)";
	jdbcUtils.setParameters(sql,student.getId(),student.getName(),student.getAge());
		
	} 

	@Override
	public void update(Student student) {
		//sql語句命令 UPDATE student_jdbc SET age=20 WHERE id=1;
				String sql = "UPDATE student_jdbc SET age=?,name=? WHERE id=?";
				jdbcUtils.setParameters(sql, student.getAge(),student.getName(),student.getId());
		
	}

	@Override
	public void delete(int id) {
		//sql語句命令 delete from student_jdbc where id=1;
		String sql = "delete from student_jdbc where id="+id+"";
		jdbcUtils.setParameters(sql);
		
	}

	@Override
	public Student findById(int id) {
		//sql語句命令 select id,name,age from student_jdbc where id=1;
		Student student = new Student();
		String sql = "select name,age from student_jdbc where id=?";
		try {
			//建立連線
			connection = jdbcUtils.getConnection();
			//建立實現方法物件
			state = connection.prepareStatement(sql);
			state.setInt(1, id);
			//實現
			update = state.executeQuery();
			while(update.next()){
				student.setId(id);
				student.setName(update.getString("name"));
				student.setAge(update.getInt("age"));
			}
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException();
		}finally {
			jdbcUtils.closeAll(connection, state, update);
		}
		return student;
		
		 
	}

	@Override
	public List<Student> findId(int index1, int index2) {
		//sql語句命令 select id,name,age from student_jdbc LIMIT 0,2;
				List<Student> list = new ArrayList<Student>();
				//Student student = new Student();
				String sql = "SELECT id,NAME,age FROM student_jdbc LIMIT ?,?;";
				try {
					//建立連線
					connection = jdbcUtils.getConnection();
					//建立實現方法物件
					state = connection.prepareStatement(sql);
					state.setInt(1, index1);
					state.setInt(2, index2);
					//實現
					update = state.executeQuery();
					while(update.next()){
						Student student = new Student();
						student.setId(update.getInt("id"));
						student.setName(update.getString("name"));
						student.setAge(update.getInt("age"));
						list.add(student);
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					throw new RuntimeException();
				}finally {
					jdbcUtils.closeAll(connection, state, update);
				}
				return list;
	}




}

package cn.test.jdbc;

import static org.junit.Assert.*;

import org.junit.Test;

import cn.IStudentDao.IStudentDao;
import cn.dao.DaoDemo;
import cn.dao.DaoDemoPrep;
import cn.student.Student;

public class TestDemo {
    //private IStudentDao stud = new DaoDemo();
	private IStudentDao stud = new DaoDemoPrep();
	@Test //
	public void testFindAll() {
		Student student = new Student();
		System.out.println(stud.findAll(student));
	}

	@Test
	public void testSave() {
		//模擬封裝
		Student student = new Student();
		student.setAge(18);
		student.setId(103);
		student.setName("jack");
		stud.save(student);
	}

	@Test //
	public void testUpdate() {
		Student student = new Student();
		student.setAge(18);
		student.setId(102);
		student.setName("Rose");
		stud.update(student);
	}

	@Test
	public void testDelete() {
		 stud.delete(103);
	}

	@Test 
	public void testFindById() {
		 System.out.println(stud.findById(6));
	}

	@Test
	public void testFindId() {
		System.out.println(stud.findId(0, 3));
	}

}