<?php
namespace MVC\MySql {
Imports("Microsoft.VisualBasic.Strings");
Imports("MVC.MySql.schemaDriver");
Imports("MVC.MySql.sqlDriver");
class MySqlExecDriver extends sqlDriver implements ISqlDriver {
function __construct(
$database,
$user,
$password,
$host = "localhost",
$port = 3306) {
parent::__construct($database, $user, $password, $host, $port);
}
public function getLastMySql() {
return parent::getLastMySql();
}
public function getLastMySqlError() {
return parent::getLastMySqlError();
}
public function getMySqlLink() {
return parent::__init_MySql(true);
}
public function ExecuteSql($SQL) {
$mysql_exec = parent::__init_MySql(false);
mysqli_select_db($mysql_exec, parent::GetDatabaseName());
mysqli_query($mysql_exec, "SET names 'utf8'");
$bench = new \Ubench();
$out = $bench->run(function() use ($mysql_exec, $SQL) {
return mysqli_query($mysql_exec, $SQL);
});
if (APP_DEBUG) {
\dotnet::$debugger->add_mysql_history($SQL, $bench->getTime(), "writes");
}
if (!$out && APP_DEBUG) {
\dotnet::$debugger->add_last_mysql_error(mysqli_error($mysql_exec));
}
$this->last_mysql_expression = $SQL;
if (\Strings::StartWith($SQL, "INSERT INTO")) {
# 尝试获取插入语句所产生的新的自增的id编号
$id = mysqli_insert_id($mysql_exec);
# 2018-6-13 在这里需要额外的注意一下,如果表之中没有自增的字段
# 则id变量可能会是false,但是insert可能是成功的,因为$out可能
# 不是false,如果直接覆盖掉会出现错误,在这里判断一下
if ($id) {
$out = $id;
}
} else {
# do nothing
}
\debugView::LogEvent("MySql query => ExecuteSql");
# 因为采用了链接缓存池,所以在这里就不再关闭链接了
# mysqli_close($mysql_exec);
return $out;
}
public function Fetch($SQL) {
$mysql_exec = parent::__init_MySql(false);
mysqli_select_db($mysql_exec, parent::GetDatabaseName());
mysqli_query($mysql_exec, "SET names 'utf8'");
$bench = new \Ubench();
$data = $bench->run(function() use ($mysql_exec, $SQL) {
return mysqli_query($mysql_exec, $SQL);
});
if (APP_DEBUG) {
\dotnet::$debugger->add_mysql_history($SQL, $bench->getTime(), "queries");
}
$this->last_mysql_expression = $SQL;
$out = null;
$resultStatus = "";
if($data) {
$out = [];
while($row = mysqli_fetch_array($data, MYSQLI_ASSOC)) {
array_push($out, $row);
}
$resultStatus = count($out) . " record";
} else {
if (APP_DEBUG) {
\dotnet::$debugger->add_last_mysql_error(mysqli_error($mysql_exec));
}
$out = false;
$resultStatus = "MySql error!";
}
# 因为采用了链接缓存池,所以在这里就不再关闭链接了
# mysqli_close($mysql_exec);
\debugView::LogEvent("MySql query => Fetch => $resultStatus");
return $out;
}
public function ExecuteScalar($SQL) {
$mysql_exec = parent::__init_MySql(false);
mysqli_select_db($mysql_exec, parent::GetDatabaseName());
mysqli_query($mysql_exec, "SET names 'utf8'");
$bench = new \Ubench();
$data = $bench->run(function() use ($mysql_exec, $SQL) {
return mysqli_query($mysql_exec, $SQL);
});
if (APP_DEBUG) {
\dotnet::$debugger->add_mysql_history($SQL, $bench->getTime(), "queries");
\debugView::LogEvent("MySql query => ExecuteScalar");
}
$this->last_mysql_expression = $SQL;
if ($data) {
while($row = mysqli_fetch_array($data, MYSQLI_ASSOC)) {
return $row;
}
} else {
return false;
}
}
}
}
?>