JDBC:createStatement(sql注入)与PrepareStatement(防止sql注入)程序案例

需求:
对数据库CRUD(增删查改)
建立一个数据库,并插入数据:
在这里插入图片描述
createStatement(sql注入):
分为student实例、接口、实现接口、测试四个部分。
在这里插入图片描述
Student.java

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 + "]";
}
   
}

IStudentDao.java

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);
}

DaoDemo.java

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 cn.IStudentDao.IStudentDao;
import cn.student.Student;

//实现接口
public class DaoDemo implements IStudentDao{

	@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 {
			//加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			//驱动类创建连接对象
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
			//创建实现方法对象
			Statement state = connection.createStatement();
			//实现
			ResultSet 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);
			}
			
			//关闭
			state.close();
			connection.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 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 {
			//加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			//驱动类创建连接对象
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
			//创建实现方法对象
			Statement state = connection.createStatement();
			//实现
			int update = state.executeUpdate(sql);
			//关闭
			state.close();
			connection.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@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 {
					//加载驱动类
					Class.forName("com.mysql.jdbc.Driver");
					//驱动类创建连接对象
					Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
					//创建实现方法对象
					Statement state = connection.createStatement();
					//实现
					int update = state.executeUpdate(sql);
					//关闭
					state.close();
					connection.close();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		
	}

	@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 {
			//加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			//驱动类创建连接对象
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
			//创建实现方法对象
			Statement state = connection.createStatement();
			//实现
			int update = state.executeUpdate(sql);
			//关闭
			state.close();
			connection.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@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 {
			//加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			//驱动类创建连接对象
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
			//创建实现方法对象
			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 (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		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 {
					//加载驱动类
					Class.forName("com.mysql.jdbc.Driver");
					//驱动类创建连接对象
					Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
					//创建实现方法对象
					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);
					}
					//关闭
					rs.close();
					state.close();
					connection.close();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return list;
	}




}

TestDemo.java

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(101);
		student.setName("jack");
		stud.save(student);
	}

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

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

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

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

}

PrepareStatement(防止sql注入)
就实现接口类改变一下。

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.sql.Statement;
import java.util.ArrayList;
import java.util.List;



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

//实现接口
public class DaoDemoPrep implements IStudentDao{

	@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 {
			//加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			//驱动类创建连接对象
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
			//创建实现方法对象
			PreparedStatement state = connection.prepareStatement(sql);
			//实现
			ResultSet 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);
			}
			
			//关闭
			state.close();
			connection.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 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 (?,?,?)";
		try {
			//加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			//驱动类创建连接对象
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
			//创建实现方法对象
			PreparedStatement state = connection.prepareStatement(sql);
			//设置参数
			state.setInt(1,student.getId());
			state.setString(2, student.getName());
			state.setInt(3, student.getAge());
			//实现
			int update = state.executeUpdate();
			//关闭
			state.close();
			connection.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@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=?";
				try {
					//加载驱动类
					Class.forName("com.mysql.jdbc.Driver");
					//驱动类创建连接对象
					Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
					//创建实现方法对象
					PreparedStatement state = connection.prepareStatement(sql);
					state.setInt(1,student.getAge());
					state.setString(2, student.getName());
					state.setInt(3, student.getId());
					//实现
					int update = state.executeUpdate();
					//关闭
					state.close();
					connection.close();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		
	}

	@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=?";
		try {
			//加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			//驱动类创建连接对象
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
			//创建实现方法对象
			PreparedStatement state = connection.prepareStatement(sql);
			state.setInt(1, id);
			//实现
			int update = state.executeUpdate();
			//关闭
			state.close();
			connection.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@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 {
			//加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			//驱动类创建连接对象
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
			//创建实现方法对象
			PreparedStatement state = connection.prepareStatement(sql);
			state.setInt(1, id);
			//实现
			ResultSet rs = state.executeQuery();
			while(rs.next()){
				student.setId(id);
				student.setName(rs.getString("name"));
				student.setAge(rs.getInt("age"));
			}
			//关闭
			rs.close();
			state.close();
			connection.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		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 {
					//加载驱动类
					Class.forName("com.mysql.jdbc.Driver");
					//驱动类创建连接对象
					Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc","root","root");
					//创建实现方法对象
					PreparedStatement state = connection.prepareStatement(sql);
					state.setInt(1, index1);
					state.setInt(2, index2);
					//实现
					ResultSet rs = state.executeQuery();
					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);
					}
					//关闭
					rs.close();
					state.close();
					connection.close();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return list;
	}

}

TestDemo.java

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(101);
		student.setName("jack");
		stud.save(student);
	}

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

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

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

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

}


程序中有很多重复的地方,可以写一个工具类,优化代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、JDBC(Java Database Connection):java连接数据库统一接口API,底层主要通过直接的JDBC驱动和 JDBC-ODBC桥驱动实现与数据库的连接。 1>.JDBC驱动程序类型: <1>.JDBC-ODBC桥加ODBC驱动程序:需要ODBC驱动,适合于企业网或三层结构应用程序 <2>.本地API:需要驱动程序的二进制代码支持 <3>.JDBC网络纯java驱动程序:将JDBC转换为与DBMS无关的网络协议,又被某服务器转换为一种DBMS 协议,以操作各种数据库 <4>.本地协议纯java驱动程序:将JDBC调用直接转换成JDBC所使用的网络协议 2、JDBC操作基本流程: 1>.导入驱动:实例化时自动向DriverManager注册(DriverManager.registerDriver()) <1>.Class.forName(driver) <2>.Class.forName(driver).newInstance() <3>.new driver() 2>.取得数据库连接(Connect to the DataBase) <1>.用DriverManager取数据库连接 Connection cn = DriverManager.getConnection(url,uid,pwd); <2>.用jndi(java的命名和目录服务)方式:多用于jsp Context ctx = (Context) new InitialContext().lookup("java:comp/env"); DataSource ds = (DataSource) ctx.lookup(jndi); Connection cn = ds.getConnection(); 3>.执行sql语句(Execute the SQL) <1>.用Statement来执行sql语句 Statement sm = cn.createStatement(); sm.executeQuery(sql); // 执行数据查询语句(select) sm.executeUpdate(sql); // 执行数据更新语句(delete、update、insert、drop等) <2>.用PreparedStatement来执行sql语句 String sql = "insert into user (id,name) values (?,?)"; PreparedStatement ps = cn.prepareStatement(sql); ps.setInt(1,xxx); ps.setString(2,xxx); ... ResultSet rs = ps.executeQuery(); // 查询 int c = ps.executeUpdate(); // 更新 4>.处理执行结果: <1>.查询语句,返回记录集ResultSet <2>.更新语句,返回数字,表示该更新影响的记录数 <3>.ResultSet的方法:while(re.next()) next(),将游标往后移动一行,如果成功返回true;否则返回false getInt("id")或getSting("name"),返回当前游标下某个字段的值 5>.释放数据库连接 rs.close(); ps.close(); /stat.close(); con.close(); 3、创建可滚动、更新的记录集 1>.创建Statement时指定参数:该Statement取得的ResultSet就是可滚动的 Statement sm = cn.createStatement(ResultSet.TYPE_SCROLL_ENSITIVE, ResultSet.CONCUR_READ_ONLY); 2>.创建PreparedStatement时指定参数 PreparedStatemet ps = cn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs.absolute(9000);

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值