php怎么跟mysql長(zhǎng)期連接

小億
139
2023-08-31 16:03:08
欄目: 云計(jì)算

在PHP中,可以使用mysqliPDO來(lái)建立長(zhǎng)期連接到MySQL數(shù)據(jù)庫(kù)。以下是使用mysqliPDO建立長(zhǎng)期連接的示例代碼:

使用mysqli建立長(zhǎng)期連接:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 建立長(zhǎng)期連接
$mysqli = new mysqli($servername, $username, $password, $dbname, null, '/path/to/mysql/socket');
if ($mysqli->connect_errno) {
die("連接失敗: " . $mysqli->connect_error);
}
// 執(zhí)行數(shù)據(jù)庫(kù)操作
// 關(guān)閉連接
$mysqli->close();
?>

使用PDO建立長(zhǎng)期連接:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 建立長(zhǎng)期連接
$dsn = "mysql:host=$servername;dbname=$dbname;charset=utf8";
$options = [
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
die("連接失敗: " . $e->getMessage());
}
// 執(zhí)行數(shù)據(jù)庫(kù)操作
// 關(guān)閉連接
$pdo = null;
?>

無(wú)論使用mysqli還是PDO,將PDO::ATTR_PERSISTENT選項(xiàng)設(shè)置為true可以建立長(zhǎng)期連接。長(zhǎng)期連接將在腳本執(zhí)行完畢后保持打開(kāi)狀態(tài),以便在后續(xù)請(qǐng)求中重復(fù)使用,以提高性能。

0