mysql的PreparedStatement

本文探讨了在MySQL中使用预处理语句时不同配置的影响。通过对比useServerPrepStmts参数设置为true和false的情况,展示了客户端如何向服务器发送SQL语句及参数,并通过Wireshark抓包验证了这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境为
mysql 5.1.39
mysql-connector-j 5.1.11
测试代码

public static void main(String[] args) throws Exception {
Connection conn = getConnection();

PreparedStatement ps = conn
.prepareStatement("select * from test where name=?");
ps.setInt(1, 1);
ps.execute();

Statement stmt = conn.createStatement();

stmt.execute("select * from test where name=1");

conn.commit();
conn.close();

}

private static Connection getConnection() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db_test?useServerPrepStmts=false",
"db_test", "db_test");
conn.setAutoCommit(false);
return conn;
}

在mysql驱动url中如果设置useServerPrepStmts=false,那么上面两条语句执行时,向服务器发送的数据包一样(用wireshark抓包工具加断点看到)。
如果设置useServerPrepStmts=true,那么执行conn.prepareStatement("select * from test where name=?");语句时,会向服务器发送命令,告知这条语句,执行ps.execute();时则只发送参数和语句编号。此时在服务器端
mysql> show global status like 'Com_stmt%' ;
可以看到 Com_stmt_prepare数量增加。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值