Python语言,MySQL数据库;外卖app系统设计与实现
由于篇幅限制,这里提供一个简化版本的代码示例,展示如何使用Python连接MySQL数据库,并实现基本的数据增删改查操作。
import pymysql
# 连接数据库
connection = pymysql.connect(host='localhost', user='your_username', password='your_password', db='your_dbname')
try:
# 创建游标对象
with connection.cursor() as cursor:
# 创建数据表
create_table_query = """
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
"""
cursor.execute(create_table_query)
# 插入数据
insert_query = """
INSERT INTO `users` (`name`, `email`) VALUES (%s, %s);
"""
record_to_insert = ('John Doe', 'johndoe@example.com')
cursor.execute(insert_query, record_to_insert)
# 查询数据
read_query = """
SELECT * FROM `users`;
"""
cursor.execute(read_query)
results = cursor.fetchall()
for row in results:
print(row)
# 更新数据
update_query = """
UPDATE `users` SET `name` = %s WHERE `id` = %s;
"""
new_name = ('Jane Doe', 1)
cursor.execute(update_query, new_name)
# 删除数据
delete_query = """
DELETE FROM `users` WHERE `id` = %s;
"""
cursor.execute(delete_query, (2,))
# 提交事务
connection.commit()
except pymysql.MySQLError as e:
print(f"Error: {e}")
finally:
# 关闭数据库连接
connection.close()
这段代码展示了如何使用Python连接MySQL数据库,创建一个数据表,执行增删改查操作,并在最后关闭数据库连接。注意,在实际应用中,你需要根据自己的数据库配置填写正确的用户名、密码和数据库名。
评论已关闭