第28次文章:简单了解JDBC(续上周)

  • 2019 年 10 月 8 日
  • 筆記

这周的学习紧接上周学习文章哈!


在上次文章的末尾,我们提到了使用Statement接口时,可能发生SQL注入,不建议各位同学使用,为了解决SQL注入问题,我们使用另一种接口PreparedStatement()。(详细情况请看上一篇文章:第27次文章:简单了解JDBC)。

下面我们直接给出测试代码:

import com.mysql.jdbc.Connection;  /**   * 测试preparedStatement的基本用法   */  public class Demo03 {    public static void main(String[] args) {      Connection conn = null;      PreparedStatement ps = null;      try {        //加载驱动类        Class.forName("com.mysql.jdbc.Driver");        conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc", "root", "123456");          String sql = "insert into t_user1 (username,pwd,regTime) value (?,?,?)";        ps = conn.prepareStatement(sql);  //      ps.setString(1, "peng");//参数索引是从1开始,而不是0  //      ps.setString(2, "123456");  //      ps.setDate(3, new java.sql.Date(System.currentTimeMillis()));//获取当前时间        System.out.println("插入一条语句");          ps.setObject(1, "peng");        ps.setObject(2, "123456");        ps.setObject(3, new java.sql.Date(System.currentTimeMillis()));//获取当前时间        } catch (ClassNotFoundException e) {        e.printStackTrace();      } catch (SQLException e) {        e.printStackTrace();      }finally {        try {          if(conn != null) {            conn.close();          }        } catch (SQLException e) {          e.printStackTrace();        }        try {          if(ps != null) {            ps.close();          }        } catch (SQLException e) {          e.printStackTrace();        }      }    }  }

tips:

1.当我们将Statement接口转换为PreparedStatement之后,我们在传入参数的时候,使用的不再是拼字符串的方法,而是在SQL命令中的参数位置加入“?”,“?”代表着占位符。这就属于PreparedStatement防止SQL注入的关键所在。正如我们在注释掉的上段代码中写的那样,使用PreparedStatement对象ps的setString,setDate等等方法来向每一个占位符的位置传递参数,此时,我们可以通过对传递的参数进行预判断,判断传入的参数是否符合String,int类型等等,这样就防止了向SQL语句中传入恶意指令情况的发生。

2.在向SQL语句中输入参数的时候,我们不但可以使用setXXX的方法,还可以直接使用setObject()的方法传递参数,此时就可以不用考虑不同类型参数的问题了,全部当做Object类型进行传递。

3.在使用setDate()方法的时候,需要使用数据库中的时间类型java.sql.Date,需要注意的是,我们传入的时间类型并不是java中的Date类型。

(5)Result接口

-Statement执行SQL语句返回Result结果集。

-Result提供的检索不同类型字段的方法,常用的有:

  • getString():获得在数据库里是varchar、char等数据库类型的对象
  • getFloa():获得数据库里是Float类型的对象
  • getDate():获得数据库里是Date类型的对象
  • getBoolean():获得数据库里是Boolean类型的对象

测试Result接口:

import com.mysql.jdbc.Connection;  /**   * 测试ResultSet结果集的基本用法   */  public class Demo04 {    public static void main(String[] args) {      Connection conn = null;      PreparedStatement ps = null;      ResultSet rs = null;      try {        //加载驱动类        Class.forName("com.mysql.jdbc.Driver");        conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc", "root", "123456");        String sql = "select id,username,pwd from t_user where id>?";        ps = conn.prepareStatement(sql);        ps.setObject(1, 1);//取出所有id大于等于2的记录        rs = ps.executeQuery();        while(rs.next()) {          System.out.println(rs.getInt(1)+"---"+rs.getString(2)+"---"+rs.getInt(3));//一次取出第1列,第2列,第3列        }      } catch (ClassNotFoundException e) {        e.printStackTrace();      } catch (SQLException e) {        e.printStackTrace();      }finally {        try {          if(conn != null) {            conn.close();          }        } catch (SQLException e) {          e.printStackTrace();        }        try {          if(ps != null) {            ps.close();          }        } catch (SQLException e) {          e.printStackTrace();        }        try {          if(rs != null) {            rs.close();          }        } catch (SQLException e) {          e.printStackTrace();        }      }    }  }

tips:

1.在这段代码中,我们依然使用PreparedStatement类型进行传输参数,使用“?”占位符,向占位符中传递我们需要大于的参数值。

2.在我们使用Result接口的时候,我们可以将其类比为一个容器,接纳所返回id大于2的结果。再编写一个while循环将结果集中的内容输出。其中的rs.next()方法类似于迭代器中的hasNext()方法。

(6)依序关闭使用的对象及连接

Result——>Statement——>Connection

(7)批处理

-Batch

-对于大量的批处理,建议使用Statement,因为PrepareStatement的预编译空间有限,当数据量特别大时,会发生异常。

测试批处理操作:

import com.mysql.jdbc.Connection;  /**   * 测试批处理的基本用法   */  public class Demo05 {    public static void main(String[] args) {      Connection conn = null;      Statement stmt = null;      ResultSet rs = null;      try {        //加载驱动类        Class.forName("com.mysql.jdbc.Driver");        conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc", "root", "123456");        conn.setAutoCommit(false); //设为手动提交        long start = System.currentTimeMillis();        stmt = conn.createStatement();          for (int i=0;i<2000;i++) {          stmt.addBatch("insert into t_user (username,pwd,regTime) values ('peng"+i+"',666,now())");        }        stmt.executeBatch();        conn.commit(); //提交事务        long end = System.currentTimeMillis();        System.out.println("插入两万条语句,耗时(毫秒):"+(end - start));      } catch (ClassNotFoundException e) {        e.printStackTrace();      } catch (SQLException e) {        e.printStackTrace();      }finally {        try {          if(conn != null) {            conn.close();          }        } catch (SQLException e) {          e.printStackTrace();        }        try {          if(stmt != null) {            stmt.close();          }        } catch (SQLException e) {          e.printStackTrace();        }        try {          if(rs != null) {            rs.close();          }        } catch (SQLException e) {          e.printStackTrace();        }      }    }  }

结果图:

tips:

在批处理需要注意的两点,第一就是需要将PreparedStatement接口更换为Statement接口,另一个需要注意的点是,需要将链接的事务提交设为手动提交。