JDBC:预编译Statement

使用PreparedStatement

  • 可以设置参数,不用字符串拼接,简化书写
  • 有预编译机制,性能比Statement更快
  • 可以防止SQL注入式攻击

练习-性能比较

  • 向数据库中插入1000条数据,比较Statement和PreparedStatement的性能差异
package jdbc;

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

public class TestJDBC {

    public static void main(String[] args) {
        
        // demo1();
        // demo2();
        
        // 加载数据库驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        int count = 1000;
        long start = System.currentTimeMillis();
        insertByPreparedStatement(count);
        long end = System.currentTimeMillis();
        System.out.printf("使用预编译Statement插入%d条数据,耗时:%d毫秒%n", count, end - start);
        
        start = System.currentTimeMillis();
        insertStatement(count);
        end = System.currentTimeMillis();
        System.out.printf("使用Statement插入%d条数据,耗时:%d毫秒%n", count, end - start);
    }

    private static void insertStatement(int count) {
        try (
                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");
                Statement s = c.createStatement();
            ) 
            {
                for (int i = 0; i < count; i++) {
                    String sql = "insert into hero values(null," + "'提莫'" + "," + i + "," + i + ")";
                    s.execute(sql);
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

    private static void insertByPreparedStatement(int count) {
        String sql = "insert into hero values(null, ?, ?, ?)";
        //建立连接
        try (
            Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");
            PreparedStatement ps = c.prepareStatement(sql);
        ) 
        {
            for (int i = 0; i < count; i++) {
                ps.setString(1, "提莫");
                ps.setFloat(2, 319.0f);
                ps.setInt(3, 50);
                ps.execute();       
            }
        }
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
image.png

你可能感兴趣的:(JDBC:预编译Statement)