python操作mysql实现一个超市管理系统

  

Python操作MySQL实现超市管理系统

简介

MySQL 是一个流行的关系型数据库管理系统,而 Python 是一种与 MySQL 配合非常好的编程语言。在这个教程中,我们将使用 Python 中的 pymysql 库实现一个超市管理系统。

步骤

1. 创建数据库和表

首先需要创建一个数据库,并且在其中创建一个表来存储超市的商品信息。可以使用如下 SQL 语句来创建一个名为 supermarket 的数据库和名为 products 的表:

CREATE DATABASE supermarket;

USE supermarket;

CREATE TABLE products (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255),
  price FLOAT
);

2. 连接数据库

使用 Python 中的 pymysql 库连接到数据库:

import pymysql

conn = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    db='supermarket'
)

其中,host 是数据库的主机名,user 是数据库的用户名,password 是数据库的密码,db 是要连接的数据库名。

3. 插入数据

使用 SQL 语句向表中插入数据:

cursor = conn.cursor()

# 插入单条数据
sql = "INSERT INTO products (name, price) VALUES (%s, %s)"
val = ("apple", 2.3)
cursor.execute(sql, val)

# 插入多条数据
sql = "INSERT INTO products (name, price) VALUES (%s, %s)"
val = [
    ("banana", 1.1),
    ("orange", 4.5),
    ("peach", 3.2)
]
cursor.executemany(sql, val)

conn.commit()

可以使用 cursor.execute()cursor.executemany() 来插入数据,conn.commit() 用于提交插入操作。

4. 查询数据

使用 SELECT 语句从表中查询数据:

cursor = conn.cursor()

# 查询单条数据
sql = "SELECT * FROM products WHERE name = %s"
val = ("apple", )
cursor.execute(sql, val)
result = cursor.fetchone()
print(result)

# 查询所有数据
sql = "SELECT * FROM products"
cursor.execute(sql)
result = cursor.fetchall()
print(result)

可以使用 cursor.fetchone() 来获取一条查询结果,也可使用 cursor.fetchall() 获取所有查询结果。

5. 更新数据

使用 UPDATE 语句更新表中数据:

cursor = conn.cursor()

sql = "UPDATE products SET price = 2.5 WHERE name = %s"
val = ("apple", )
cursor.execute(sql, val)

conn.commit()

可以使用 cursor.execute() 来更新数据,conn.commit() 用于提交更新操作。

6. 删除数据

使用 DELETE 语句删除表中数据:

cursor = conn.cursor()

sql = "DELETE FROM products WHERE name = %s"
val = ("apple", )
cursor.execute(sql, val)

conn.commit()

可以使用 cursor.execute() 来删除数据,conn.commit() 用于提交删除操作。

示例说明

以下是一个基于 pymysql 实现的超市管理系统示例:

import pymysql

conn = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    db='supermarket'
)

def add_product(name, price):
    cursor = conn.cursor()
    sql = "INSERT INTO products (name, price) VALUES (%s, %s)"
    val = (name, price)
    cursor.execute(sql, val)
    conn.commit()

def get_products():
    cursor = conn.cursor()
    sql = "SELECT * FROM products"
    cursor.execute(sql)
    return cursor.fetchall()

def remove_product(name):
    cursor = conn.cursor()
    sql = "DELETE FROM products WHERE name = %s"
    val = (name, )
    cursor.execute(sql, val)
    conn.commit()

# 添加商品
add_product("apple", 2.5)
add_product("banana", 1.1)
add_product("peach", 3.2)

# 查询商品
products = get_products()
print(products)

# 删除商品
remove_product("apple")
products = get_products()
print(products)

在这个示例中,我们定义了 add_product() 函数用于添加商品,get_products() 函数用于查询所有商品,以及 remove_product() 函数用于删除商品。我们使用这些函数来添加、查询和删除一些商品信息。

相关文章