1.1 参数化

1.1.1 含义

  • 也叫预编译sql
  • 把SQL语句与SQL参数进行分离
  • 优点:
    • 高效
    • 安全

1.1.2 SQL注入

  • 所谓的SQL语句就是将命令插入到表单,或者通过URL传递给浏览器
  • 缺点:
    • 恶意注入命令,欺骗服务器,造成网站被攻击
    • 安全性不是很高
  • 参数化DML语句 ```java package com.qfedu.zy3;

import org.junit.Test;

import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;

public class TestDButil { //插入 @Test public void insert(){ Connection connection = DButil.getConnection(); try { PreparedStatement psmt = connection.prepareStatement(“insert into users(username,password) values(?,?)”); psmt.setString(1,”yangyang”); psmt.setString(2,”1233”); int row = psmt.executeUpdate(); System.out.println(row); DButil.close(connection,psmt,null); } catch (SQLException e) { e.printStackTrace(); } } //删除 @Test public void delete(){ Connection connection = DButil.getConnection(); try { PreparedStatement psmt = connection.prepareStatement(“delete from users where id = ?”); psmt.setInt(1,4); int row = psmt.executeUpdate(); System.out.println(row); DButil.close(connection,psmt,null); } catch (SQLException e) { e.printStackTrace(); } } //修改 @Test public void update(){ Connection connection = DButil.getConnection(); try { PreparedStatement psmt = connection.prepareStatement(“update users set password=? where username=?”); psmt.setString(1,”8888”); psmt.setString(2,”kangkang”); int row = psmt.executeUpdate(); System.out.println(row); DButil.close(connection,psmt,null); } catch (SQLException e) { e.printStackTrace(); } } @Test public void query(){ Connection connection = DButil.getConnection(); try { PreparedStatement psmt = connection.prepareStatement(“select * from users where username = ? and password = ?”); psmt.setString(1,”kangkang”); psmt.setString(2,”8888”); ResultSet res = psmt.executeQuery(); if(res.next()){ System.out.println(res.getString(“username”)+”\t”+res.getString(“password”)); }else { System.out.println(“账户密码不匹配”); } DButil.close(connection,psmt,res); } catch (SQLException e) { e.printStackTrace(); } } }

  1. - 参数化DQL语句
  2. ```java
  3. //测试查询
  4. public static void query() throws Exception {
  5. Class.forName("com.mysql.jdbc.Driver");
  6. //创建连接
  7. String url = "jdbc:mysql://localhost:3306/empdb?useUnicode=true&characterEncoding=utf-8&useSSL=false";
  8. Connection connection =
  9. DriverManager.getConnection(url,"root","123456");
  10. //参数化SQL
  11. PreparedStatement psmt = conn.prepareStatement("select ename,job,sal from emp where sal>?");
  12. psmt.setDouble(1,2000);
  13. ResultSet rs = psmt.executeQuery();
  14. while (rs.next()){
  15. System.out.println( rs.getString("ename") + rs.getDouble("sal") );
  16. }
  17. //关闭资源
  18. rs.close();
  19. psmt.close();
  20. connection.close();
  21. }

1.2 单元测试

1.2.1 作用

  • 单元测试是对程序进行可用性测试
  • 它属于白盒测试
  • Java测试的框架就Junit

    1.2.2 使用步骤

  1. 导入jar包:
    1. junit-4.12.jar
    2. hamcrest-core-1.3.jar
  2. 只用注解:
    1. @Test 单元测试注解,带该注解的方法可用独立运行,当一个main使用
    2. @Before 在当前单元测试前执行。 做初始化操作
    3. @After 在当前单元测试后执行。 做扫尾操作
  3. 案例: ```java package com.qfedu.junit;

import org.junit.After; import org.junit.Before; import org.junit.Test;

//学习Junit的用法 public class HelloJunit { //1 导包 ok // 2 注解 @Test @Before @After

//t1 就是一个独立执行的入口
@Test
public void t1(){
    System.out.println("hello");
}
//t2 就是一个独立执行的入口
@Test
public void t2(){
    System.out.println("world");
}
@Test
public  void t3(){
    System.out.println("java");
}


@Before
public void aaa(){
    System.out.println("begin....");
}

@After
public void bbb(){
    System.out.println("end.....");
}

}

<a name="ZruP7"></a>
### 1.3 封装
<a name="pnX4f"></a>
#### 1.3.1 版本1

- 由于直接使用JDBC代码,会出现大量冗余,所以有必要进行封装
```java
package com.qfedu.util;

import java.sql.*;

//数据操作工具类
public class DButil {

    //定义数据库连接信息
    private static final  String url="jdbc:mysql://localhost:3306/empdb?useUnicode=true&characterEncoding=utf-8&useSSL=false";
    private static final  String username="root";
    private static final  String password="123456";
    private static final  String driver="com.mysql.jdbc.Driver";

    //静态代码块(执行一次)
    static{
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("加载驱动失败");
        }

    }

    // 获得数据库连接对象
    public static Connection getConnection(){
        Connection connection = null;
        try {
           connection=   DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("创建连接对象失败");
        }
        return  connection;
    }


    // 释放资源(哪些资源需要关闭,需要管的传入,没有的就传null)
    public static void close(Connection conn, Statement smt, ResultSet rs){
         if(rs!=null){
             try {
                 rs.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }

         if(smt!=null){
             try {
                 smt.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }

         if(conn!=null){
             try {
                 conn.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }
    }
}

1.3.2 版本2

  1. 导入jar包

    mysql-connector-java-5.1.48.jar
    

    2.准备配置文件db.properties在src下:

    jdbc.username=root
    jdbc.password=123456
    jdbc.url=jdbc:mysql://localhost:3306/empdb?useUnicode=true&characterEncoding=utf-8&useSSL=false
    jdbc.driver=com.mysql.jdbc.Driver
    

    3.编码: ```java package com.qfedu.jdbc; import java.sql.*; import java.util.Properties; //工具类 public class Dbutil { // 连接信息 private static String username=null; private static String url=null; private static String password=null; private static String driver=null;

    //使用连接信息(读取配置信息,什么时候去读呢?) static {

     try {
         //读取配置信息
         Properties pro = new Properties();// 准备map集合
         //把 db.properties 中的数据导入到 pro 集合中
         // 获得当前线程 Thread.currentThread()
         // 利用线程或获得类加载器(加载类) getContextClassLoader()
         // 类加载器就可以中类路径下加载资源 getResourceAsStream("db.properties")
         pro.load( Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties") );
    
         //赋值
         driver= pro.getProperty("jdbc.driver");
         username=pro.getProperty("jdbc.username");
         password=pro.getProperty("jdbc.password");
         url=pro.getProperty("jdbc.url");
    
         //加载驱动
         Class.forName(driver);
    
     }catch( Exception e){
         e.printStackTrace();
     }
    

    }

//获得连接的方法
public static Connection getConnection(){
    //准备一个空连接对象
    Connection conn =null;
    try {
        //为连接对象赋值
       conn = DriverManager.getConnection(url,username,password);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    //返回获得的连接对象,如果发生异常则返回默认值null
    return  conn;
}
//关闭资源的方法
public static void close(Connection conn){
     if(conn!=null){
         try {
             conn.close();
         } catch (SQLException e) {
             e.printStackTrace();
         }
     }
}

public static void close(Connection conn, Statement smt){

    if(smt!=null){
        try {
            smt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if(conn!=null){
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

public static void close(Connection conn, Statement smt, ResultSet rs){
    if(rs!=null){
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    if(smt!=null){
        try {
            smt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    if(conn!=null){
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

} ```