[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
一、预处理语句介绍
MySQL支持服务端预处理语句,预处理语句利用高效的客户端/服务端二进制协议。用占位符替换参数值的预处理语句有下列两个好处:
每次执行语句时,解析语句的开销更小。通常,数据库应用程序会处理大量相似的语句,只在子句中更改文字或变量值,比如查询和删除的WHERE子句,更新的UPDATE子句,插入的VALUES子句。
防止SQL注入攻击。参数值可以包含非转义的SQL引用以及分隔符号。
你可以通过客户端编程接口使用服务端的预处理语句,比如C编程时使用MySQL C API 客户端库或者MySQL Connector/C。
二、C API中预处理语句执行顺序
为了准备和执行一个语句,应用程序遵循下列步骤:
1.用mysql_stmt_init()函数创建一个预处理语句句柄。为了在服务端准备语句,需要调用mysql_stmt_prepare()并且传递一个包含SQL语句的字符串给它。
2.如果语句会产生一个结果集(a result
set),那么调用mysql_stmt_result_metadata()获取结果集的元数据(metadata)。元数据结果集指示结果中有多少列以及包含每一列的相关信息。
3.用mysql_stmt_bind_param()设置每一个参数的值。所有的参数都必须赋值,否则语句执行会返回错误或者产生意想不到的结果。
4.调用mysql_stmt_execute()执行一个语句。
5.如果语句产生一个结果集,调用mysql_stmt_bind_result()绑定数据缓存用来接收每一行的值。
6.重复调用mysql_stmt_fetch()获取每一行的数据存储到绑定的缓存。
7.需要的话重复步骤3到步骤6,通过改变参数值并重新执行语句。