MySQL是一个广泛使用的开源关系型数据库管理系统,在Web应用程序开发中得到了广泛的应用。MySQL被认为是最快、最稳定、最易于使用的关系型数据库系统之一,将大量数据存储在表格中,同时支持SQL语言,可以通过多种编程语言进行操作。
下面是关于MySQL基本使用的一些示例:
# 连接到MySQL数据库
$conn = mysqli_connect($db_host, $db_user, $db_password, $db_name);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
# 创建表格
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50),
password VARCHAR(32) NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table created successfully!";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
# 插入数据
$sql = "INSERT INTO users (name, email, password)
VALUES ('John Doe', 'johndoe@example.com', 'password123')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully!";
} else {
echo "Error: " . $sql . "
" . mysqli_error($conn);
}
# 查询数据
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) >0) {
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "
";
}
} else {
echo "0 results";
}
# 修改数据
$sql = "UPDATE users SET email='newemail@example.com' WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully!";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
# 删除数据
$sql = "DELETE FROM users WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully!";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
# 关闭连接
mysqli_close($conn);
总的来说,使用MySQL可以轻松管理和处理数据,是Web开发人员必须掌握的技能之一。