Python和mysql做个简单的数据管理系统
时间: 2024-02-26 08:58:35 浏览: 15
好的,下面是一个简单的Python和MySQL数据管理系统的示例:
首先,需要安装MySQL驱动程序,可以使用`pip`命令:
```python
pip install mysql-connector-python
```
然后,连接到MySQL数据库,并创建一个名为`employees`的表:
```python
import mysql.connector
# 建立数据库连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 创建一个名为"employees"的表
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE employees (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)")
```
接下来,可以编写一些代码来添加、编辑和删除数据:
```python
# 添加一些数据
sql = "INSERT INTO employees (name, age) VALUES (%s, %s)"
val = ("John", 25)
mycursor.execute(sql, val)
mydb.commit()
# 更新数据
sql = "UPDATE employees SET age = %s WHERE name = %s"
val = (26, "John")
mycursor.execute(sql, val)
mydb.commit()
# 删除数据
sql = "DELETE FROM employees WHERE name = %s"
val = ("John", )
mycursor.execute(sql, val)
mydb.commit()
```
最后,可以查询和显示数据:
```python
# 查询并显示数据
mycursor.execute("SELECT * FROM employees")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
完整代码如下:
```python
import mysql.connector
# 建立数据库连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 创建一个名为"employees"的表
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE employees (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)")
# 添加一些数据
sql = "INSERT INTO employees (name, age) VALUES (%s, %s)"
val = ("John", 25)
mycursor.execute(sql, val)
mydb.commit()
# 更新数据
sql = "UPDATE employees SET age = %s WHERE name = %s"
val = (26, "John")
mycursor.execute(sql, val)
mydb.commit()
# 删除数据
sql = "DELETE FROM employees WHERE name = %s"
val = ("John", )
mycursor.execute(sql, val)
mydb.commit()
# 查询并显示数据
mycursor.execute("SELECT * FROM employees")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
这是一个简单的数据管理系统示例,你可以根据自己的需求和业务逻辑进行修改和扩展。