一、使用PreparedStatement预编译语句防止SQL注入

什么是SQL注入?

所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令。

举个例子:假如我们登录时执行的SQL语句为:select *from user where username='USERNAME' and password='PASSWORD';

但是我们可以把USERNAME填写为"tom';-- ",(注意--后有空格),PASSWORD随便写(假设这里写123),这样SQL语句就成了select *from user where username='tom';-- ' and password='123';

"-- "后的内容就被注释掉,现在就算密码不正确也能查询到相应的结果。利用SQL注入可以实现数据的盗取

在Java中使用PreparedStatement类防止SQL注入

防SQL注入的方法有很多,使用预编译语句是一种简单有效的方式

下面介绍如何使用这种方式来操作数据库

我已经在本地数据库mydb中创建了一个user表,并在表中插入数据

现在我们使用字符串拼接的方式来构造一个SQL语句,并在mysql客户端执行此SQL语句,结果如下:

通过图中我们发现这种方式SQL注入成功

下面使用预编译SQL语句的方式来执行此SQL语句

  1. String url = "jdbc:mysql://localhost:3306/mydb";
  2. String user = "root";
  3. String password = "root";
  4. String username = "杜若' or 1=1; -- "; //'-- ' 是sql中的注释符号(注意后面的空格)
  5. String pwd = "000";
  6. Class.forName("com.mysql.jdbc.Driver");
  7. Connection connection = DriverManager.getConnection(url,user,password);
  8. //构造sql语句
  9. String sql = "select *from user where username=? and pwd =?";
  10. PreparedStatement pstmt = connection.prepareStatement(sql);
  11. pstmt.setString(1, username);
  12. pstmt.setString(2, pwd);
  13. ResultSet rs = pstmt.executeQuery();
  14. if(rs.next()){
  15. do{
  16. String username = rs.getString(2);
  17. String pwd = rs.getString(3);
  18. System.out.println(username+":"+pwd);
  19. }while(rs.next());
  20. }else{
  21. System.out.println("未查到相应的结果");
  22. }
  23. if(rs!=null){
  24. rs.close();
  25. }
  26. if(pstmt!=null){
  27. pstmt.close();
  28. }
  29. if(connection!=null){
  30. connection.close();
  31. }

测试运行之后的结果

这样已经达到了防SQL注入的目的

那为什么它这样处理就能预防SQL注入提高安全性呢?其实是因为SQL语句在程序运行前已经进行了预编译,在程序运行时第一次操作数据库之前,SQL语句已经被数据库分析,编译和优化,对应的执行计划也会缓存下来并允许数据库已参数化的形式进行查询,当运行时动态地把参数传给PreprareStatement时,即使参数里有敏感字符如 or '1=1'也数据库会作为一个参数一个字段的属性值来处理而不会作为一个SQL指令

二,获取插入自增长值

有时候在插入一条记录的时候,我们需要获取插入这条数据的自增长值,以便在其他地方使用

直接上代码

  1. //获取插入自增长
  2. public class Demo1 {
  3. private String user="root";
  4. private String password="root";
  5. private String url="jdbc:mysql://localhost:3306/mydb";
  6. @Test
  7. public void test1() throws Exception{
  8. Class.forName("com.mysql.jdbc.Driver");
  9. Connection connection = DriverManager.getConnection(url, user, password);
  10. String sql = "insert into user(username,pwd) values(?,?)";
  11. //第二个参数是Statement类中的一个常量,指示是否应该返回自动生成的键的标志
  12. PreparedStatement pstmt = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
  13. pstmt.setString(1, "mary");
  14. pstmt.setString(2, "123456");
  15. pstmt.executeUpdate();
  16. ResultSet rs = pstmt.getGeneratedKeys();
  17. if(rs.next()){
  18. int key = rs.getInt(1);
  19. System.out.println(key);
  20. }
  21. if(rs!=null){
  22. rs.close();
  23. }
  24. if(pstmt!=null){
  25. pstmt.close();
  26. }
  27. if(connection!=null){
  28. connection.close();
  29. }
  30. }
  31. }

三,批处理执行

有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。

无论使用Statement对象还是使用PreparedStatement对象都可以实现

这里介绍使用PreparedStatement来实现的方式

  1. 获取PreparedStatement对象
  2. 设置每条批处理的参数
  3. 将一组参数添加到批处理命令中

下面上实例代码

  1. public class Demo1 {
  2. private String user="root";
  3. private String password="root";
  4. private String url="jdbc:mysql://localhost:3306/mydb";
  5. @Test
  6. public void test1() throws Exception{
  7. List<User> list = new ArrayList<User>();
  8. for(int i = 0;i < 10;i++){
  9. User user = new User();
  10. user.setUsername("albee"+i);
  11. user.setPwd("123456");
  12. list.add(user);
  13. }
  14. sava(list);
  15. }
  16. public void sava(List<User> l) throws Exception{
  17. Class.forName("com.mysql.jdbc.Driver");
  18. Connection connection = DriverManager.getConnection(url, user, password);
  19. String sql = "insert into user(username,pwd) values(?,?)";
  20. PreparedStatement pstmt = connection.prepareStatement(sql);
  21. for(int i = 0;i<l.size();i++){
  22. pstmt.setString(1, l.get(i).getUsername());
  23. pstmt.setString(2, l.get(i).getPwd());
  24. pstmt.addBatch();
  25. // 每到五条就执行一次对象集合中的批处理命令,
  26. if(i%5==0){
  27. pstmt.executeBatch();
  28. pstmt.clearBatch();
  29. }
  30. }
  31. // 不足五条也要执行一次
  32. pstmt.executeBatch();
  33. pstmt.clearBatch();
  34. if(pstmt!=null){
  35. pstmt.close();
  36. }
  37. if(connection!=null){
  38. connection.close();
  39. }
  40. }
  41. }

四,事务的操作

有时候我们需要完成一组数据库操作,这其中的操作有一个失败则整个操作就回滚,即组成事务的每一个操作都执行成功整个事务才算成功执行

常见的例子就是银行转帐业务

update account set money=money-1000 where accountName='张三';

update account set money=money+1000 where accountName='李四';

已经在mydb中创建了account表,包含accountName和money字段,并插入了两条记录

实例代码:

  1. // 使用事务
  2. @Test
  3. public void test2(){
  4. String url = "jdbc:mysql://localhost:3306/mydb";
  5. String user = "root";
  6. String password = "root";
  7. try {
  8. Class.forName("com.mysql.jdbc.Driver");
  9. connection = DriverManager.getConnection(url,user,password);
  10. connection.setAutoCommit(false); //设置事务为手动提交
  11. String sql_zs = "update account set money=money-1000 where accountName='张三'";
  12. String sql_ls = "update account set money=money+1000 where accountName='李四'";
  13. pstmt = connection.prepareStatement(sql_ls);
  14. int count_ls = pstmt.executeUpdate();
  15. pstmt = connection.prepareStatement(sql_zs);
  16. int count_zs = pstmt.executeUpdate();
  17. }catch (Exception e) {
  18. e.printStackTrace();
  19. try {
  20. connection.rollback();
  21. } catch (Exception e2) {
  22. e2.printStackTrace();
  23. }
  24. } finally {
  25. try {
  26. connection.commit();
  27. } catch (SQLException e1) {
  28. e1.printStackTrace();
  29. }
  30. if(pstmt!=null){
  31. try {
  32. pstmt.close();
  33. } catch (SQLException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. if(connection!=null){
  38. try {
  39. connection.close();
  40. } catch (SQLException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }

如果事务执行成功

执行前和执行后表的变动

JDBC加强的更多相关文章

  1. Java数据库连接技术——JDBC

    大家好,今天我们学习了Java如何连接数据库.之前学过.net语言的数据库操作,感觉就是一通百通,大同小异. JDBC是Java数据库连接技术的简称,提供连接各种常用数据库的能力. JDBC API ...

  2. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

  3. [原创]java使用JDBC向MySQL数据库批次插入10W条数据测试效率

    使用JDBC连接MySQL数据库进行数据插入的时候,特别是大批量数据连续插入(100000),如何提高效率呢?在JDBC编程接口中Statement 有两个方法特别值得注意:通过使用addBatch( ...

  4. JDBC MySQL 多表关联查询查询

    public static void main(String[] args) throws Exception{ Class.forName("com.mysql.jdbc.Driver&q ...

  5. JDBC增加删除修改

    一.配置程序--让我们程序能找到数据库的驱动jar包 1.把.jar文件复制到项目中去,整合的时候方便. 2.在eclipse项目右击"构建路径"--"配置构建路径&qu ...

  6. JDBC简介

    jdbc连接数据库的四个对象 DriverManager  驱动类   DriverManager.registerDriver(new com.mysql.jdbc.Driver());不建议使用 ...

  7. JDBC Tutorials: Commit or Rollback transaction in finally block

    http://skeletoncoder.blogspot.com/2006/10/jdbc-tutorials-commit-or-rollback.html JDBC Tutorials: Com ...

  8. FineReport如何用JDBC连接阿里云ADS数据库

    在使用FineReport连接阿里云的ADS(AnalyticDB)数据库,很多时候在测试连接时就失败了.此时,该如何连接ADS数据库呢? 我们只需要手动将连接ads数据库需要使用到的jar放置到%F ...

  9. JDBC基础

    今天看了看JDBC(Java DataBase Connectivity)总结一下 关于JDBC 加载JDBC驱动 建立数据库连接 创建一个Statement或者PreparedStatement 获 ...

  10. Spring学习记录(十四)---JDBC基本操作

    先看一些定义: 在Spring JDBC模块中,所有的类可以被分到四个单独的包:1.core即核心包,它包含了JDBC的核心功能.此包内有很多重要的类,包括:JdbcTemplate类.SimpleJ ...

随机推荐

  1. 初识python: 文件下载进度

    (后续待更新...) 使用 request 的 urlretrieve 方法创建"回调函数": 下载进度 详细代码如下: #!/user/bin env python # auth ...

  2. 谈谈 StringBuffer 和 StringBuilder 的历史故事

    1.前言 众所周知,StringBuffer 是线程安全的 ,而StringBuilder 不是线程安全的  ,但是 StringBuilder 速度会更快. 事实上 作为一个字符串拼接 方法 ,在线 ...

  3. icmpsh之icmp反弹shell

    一,技术原理 向ping www.baidu.com时,本机会先向百度的服务器发送ICMP请求包,如果请求成功了,则百度服务器会回应ICMP的响应包 引用百度百科: ICMP(Internet Con ...

  4. 使用.NET 6开发TodoList应用(31)——实现基于Github Actions和ACI的CI/CD

    系列导航及源代码 使用.NET 6开发TodoList应用文章索引 需求和目标 在这个系列的最后一节中,我们将使用GitHub Actions将TodoList应用部署到Azure Container ...

  5. github与gitlab创建新仓库

    github创建新仓库 然后根据下一页的命令提示进行即可 gitlab创建新仓库 git init git remote add origin git@***.***.**.**:user/proje ...

  6. Microsoft Store 桌面应用发布流程(一)之打包应用

    这篇博客主要是介绍桌面应用打包的流程,应用发布流程请看 Microsoft Store 桌面应用发布流程(二)之提交应用 1. 创建打包项目 打开现有的桌面应用项目.选择解决方案项目,右键选择 添加新 ...

  7. Solon Web 开发,十一、国际化

    Solon Web 开发 一.开始 二.开发知识准备 三.打包与运行 四.请求上下文 五.数据访问.事务与缓存应用 六.过滤器.处理.拦截器 七.视图模板与Mvc注解 八.校验.及定制与扩展 九.跨域 ...

  8. 【记录一个问题】opencl的clGetPlatformIDs()在cuda 9下返回-1001(找不到GPU平台)

    如题:在cuda9, nvidia驱动版本 384.81 的环境下运行opencl程序,在clGetPlatformIDs()函数中返回-1001错误. 把环境更换为cuda 10,驱动版本410.1 ...

  9. synergy最佳解决方案——barrier

    synergy最佳解决方案--barrier ​ 不知道大家有没有一套键盘鼠标控制多台电脑的需求,主流的硬件或说软件有大神整理如下: 软件方案: Windows 之间:Mouse Without Bo ...

  10. 关于cmake和开源项目发布的那些事(PF)

    本来是打算写一篇年终总结,随便和以往一样提一提自己的开源项目(长不大的plain framework)的一些进度,不过最近这一年对于这个项目实在是维护不多,实在难以用它作为醒目的标题.而最近由于使用了 ...