数据库操作中的“增删改查”指的是对数据库中的数据进行四种基本操作:
以下是一个使用Python和MySQL进行增删改查操作的简单示例:
import mysql.connector
# 连接到MySQL数据库
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = db.cursor()
# 增(Create)
sql_insert = "INSERT INTO users (name, email) VALUES (%s, %s)"
values = ("John Doe", "john@example.com")
cursor.execute(sql_insert, values)
db.commit()
# 查(Read)
sql_select = "SELECT * FROM users WHERE name = %s"
cursor.execute(sql_select, ("John Doe",))
result = cursor.fetchall()
for row in result:
print(row)
# 改(Update)
sql_update = "UPDATE users SET email = %s WHERE name = %s"
cursor.execute(sql_update, ("john_new@example.com", "John Doe"))
db.commit()
# 删(Delete)
sql_delete = "DELETE FROM users WHERE name = %s"
cursor.execute(sql_delete, ("John Doe",))
db.commit()
# 关闭数据库连接
cursor.close()
db.close()
try-except
块捕获异常并打印错误信息。commit()
方法提交事务。rollback()
方法回滚事务。通过以上示例和解释,你应该能够理解数据库增删改查的基本概念、优势、类型、应用场景以及常见问题的解决方法。
领取专属 10元无门槛券
手把手带您无忧上云