日期:2014-05-16 浏览次数:20870 次
数据库执行sql之前首先需要编译sql语句,之后通过DBMS执行编译后的语句。我们知道编译sql是需要时间的,如果同一时刻要执行多条sql语句,那么编译就需要很长时间,而这种时间的开销会造成程序性能的下降如并发,这个问题如果用mysql扩展库是没办法解决的但是mysqli可以,这或许就是mysqli扩展库比较优秀的地方。mysqli扩展库的这种处理类似jdbc的preparedstatement.下面就按我的方式来分享下这块知识。
1.编译sql语句,mysqli扩展库可以使用prepare()来预编译sql,该方法需要传入我们的sql,代码如下
$pstmt=$mysqli->prepare($sql);
$id=3;
//绑定参数
$pstmt->bind_param("i",$id);
$pstmt->execute();
//绑定参数
$pstmt->bind_param("i",$id);
$pstmt->execute();
$pstmt->bind_result($stuName,$stuId);
while($pstmt->fetch()){
echo "---$stuName--$stuId"."<br>";
}
$pstmt->free_result(); $pstmt->close(); $mysqli->close();
代码看起来有点散,下面我把全部代码贴出来
<?php
$mysqli=new mysqli("localhost", "root", "123456","student");
if($mysqli->connect_error){
die("数据库连接失败:".$mysqli->connect_error);
}
$sql="select stuName,stuId from m_student where id=?";
$pstmt=$mysqli->prepare($sql);
$id=3;
//绑定参数
$pstmt->bind_param("i",$id);
$pstmt->execute();
$pstmt->bind_result($stuName,$stuId);
while($pstmt->fetch()){
echo "---$stuName--$stuId"."<br>";
}
$pstmt->free_result();
$pstmt->close();
$mysqli->close();
?>
。