农妇山泉一亩田 发表于 3 天前

Java程序使用预处理语句的性能提升

Java程序使用预处理语句的性能提升

GreatSQL提供了对服务器端预处理语句(Prepared Statements)的支持。预处理语句可以利用了高效的客户机/服务器二进制协议。使用带有参数值占位符的预处理语句有以下好处:

[*]每次执行时剖析语句的开销更少。通常,数据库应用程序处理大量几乎相同的语句,只对语句中的笔墨值或变量值进行更改,如 SELECT 和 UPDATE 中的 WHERE,UPDATE 语句中的 SET 和 INSERT 语句中的VALUES。
[*]防范SQL注入攻击。参数值可以包含未转义的SQL引号和分隔符。
本文编写Java程序,执行常规SQL语句和预处理语句,对比性能差异,量化预处理语句的性能提升。
1. 程序设计

通过Java程序进行DML操纵,每次DML的数量是10万条,每50条一个提交批次。对比执行预处理语句和普通SQL语句,通过执行时间是非,判断执行的性能。

[*]函数 testInsertPerformance 对比 INSERT 性能;
[*]函数 testUpdatePerformance 对比 UPDATE 性能;
[*]函数 testSelectPerformance 对比 SELECT 性能;
[*]函数 testDeletePerformance 对比 DELETE 性能;
1.1 测试表

greatsql> CREATE DATABASE IF NOT EXISTS testdb1;
greatsql> USE testdb1;

greatsql> CREATE TABLE IF NOT EXISTS test_table (
    id INT AUTO_INCREMENT PRIMARY KEY,
    col1 INT,
    col2 VARCHAR(100),
    col3 DATETIME
);1.2 Java程序代码

Java程序比力轻易使用预处理SQL语句,主要有两点:

[*]数据库连接字符串中增加useServerPrepStmts=true;
[*]SQL语句使用conn.prepareStatement进行预处理;
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;import java.sql.Timestamp;import java.util.Date;public class SqlPerformanceTest {    private static final String URL = "jdbc:mysql://192.168.134.208:3307/testdb1?useServerPrepStmts=true";    private static final String USER = "testuser";    private static final String PASSWORD = "testpass";    private static final int NUM_ITERATIONS = 100000;    private static final int BATCH_SIZE = 50;    public static void main(String[] args) {      try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {            // 清空测试表            clearTable(conn);            // 测试 INSERT 操纵            testInsertPerformance(conn);            // 测试 UPDATE 操纵            testUpdatePerformance(conn);            // 测试 SELECT 操纵            testSelectPerformance(conn);            // 测试 DELETE 操纵            testDeletePerformance(conn);      } catch (Exception e) {            e.printStackTrace();      }   }    private static void clearTable(Connection conn) throws Exception {      try (Statement stmt = conn.createStatement()) {            stmt.execute("TRUNCATE TABLE test_table");      }    }    private static void testInsertPerformance(Connection conn) throws Exception {      long startTime, endTime;      // 清空测试表      clearTable(conn);       // 普通 SQL 语句      startTime = System.nanoTime();      conn.setAutoCommit(false); // 关闭自动提交      try (Statement stmt = conn.createStatement()) {            for (int i = 1; i
页: [1]
查看完整版本: Java程序使用预处理语句的性能提升