MySQL是一種常見的關(guān)系型數(shù)據(jù)庫(kù)管理系統(tǒng),被廣泛應(yīng)用于許多應(yīng)用領(lǐng)域。對(duì)于需要使用MySQL數(shù)據(jù)庫(kù)管理的工程師和開發(fā)人員來說,熟悉MySQL必須知道的知識(shí)是非常重要的。
以下是MySQL必知必會(huì)使用的一些重點(diǎn)內(nèi)容:
//連接MySQL數(shù)據(jù)庫(kù) $mysqli = new mysqli('localhost', 'username', 'password', 'database'); if ($mysqli->connect_error) { die('連接失敗:' . $mysqli->connect_error); } //創(chuàng)建表 $sql = "CREATE TABLE `users` ( `id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"; if ($mysqli->query($sql) === TRUE) { echo "表創(chuàng)建成功"; } else { echo "表創(chuàng)建失敗:" . $mysqli->error; } //插入數(shù)據(jù) $sql = "INSERT INTO `users` (`username`, `password`, `email`) VALUES ('test', 'test', 'test@test.com')"; if ($mysqli->query($sql) === TRUE) { echo "插入成功"; } else { echo "插入失敗:" . $mysqli->error; } //查詢數(shù)據(jù) $sql = "SELECT * FROM `users`"; $result = $mysqli->query($sql); if ($result->num_rows >0) { while ($row = $result->fetch_assoc()) { echo "ID:" . $row['id'] . ",用戶名:" . $row['username'] . ",郵箱:" . $row['email'] . "
"; } } else { echo "查詢結(jié)果為空"; } //更新數(shù)據(jù) $sql = "UPDATE `users` SET `email`='new@test.com' WHERE `username`='test'"; if ($mysqli->query($sql) === TRUE) { echo "更新成功"; } else { echo "更新失敗:" . $mysqli->error; } //刪除數(shù)據(jù) $sql = "DELETE FROM `users` WHERE `username`='test'"; if ($mysqli->query($sql) === TRUE) { echo "刪除成功"; } else { echo "刪除失敗:" . $mysqli->error; } //關(guān)閉連接 $mysqli->close();
需要注意的是,在使用MySQL之前,必須在本地或者遠(yuǎn)程服務(wù)器上安裝并啟動(dòng)MySQL服務(wù),然后才能進(jìn)行數(shù)據(jù)庫(kù)連接和操作。