Anaconda创建school数据库,school数据库中再创建student表,teacher表,分别插入三条数据;再创建一个mysql连接,并进行输出查看。
时间: 2024-09-11 20:04:12 浏览: 65
在Anaconda环境中,我们可以利用Python的pymysql库来创建数据库和表,并添加数据。以下是一步步的操作说明:
**第一步:创建数据库**
```python
import pymysql
# 创建连接
db = pymysql.connect(host='localhost', user='root', password='your_password', port=3306, charset='utf8mb4')
try:
# 创建游标对象
cursor = db.cursor()
# 创建school数据库,如果已存在则跳过
cursor.execute("CREATE DATABASE IF NOT EXISTS school DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
# 切换到新创建的数据库
cursor.execute(f"USE school")
# 创建student和teacher表
create_student_table = """
CREATE TABLE IF NOT EXISTS student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT
)
"""
create_teacher_table = """
CREATE TABLE IF NOT EXISTS teacher (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
subject VARCHAR(100)
)
"""
cursor.execute(create_student_table)
cursor.execute(create_teacher_table)
except Exception as e:
print(f"Error occurred: {str(e)}")
finally:
# 关闭游标和连接
cursor.close()
db.close()
```
这里假设数据库管理员账户是root,密码是`your_password`,如果你使用的是其他账号,请替换相应信息。
**第二步:插入数据**
接着,你可以添加一些示例数据。下面是在`student`表和`teacher`表各插入一条数据的例子:
```python
insert_student = "INSERT INTO student (name, age) VALUES ('Alice', 18)"
insert_teacher = "INSERT INTO teacher (name, subject) VALUES ('Bob', 'Math')"
cursor.execute(insert_student)
cursor.execute(insert_teacher)
# 提交事务
db.commit()
```
**第三步:查看数据**
最后,可以使用`SELECT`语句查询数据:
```python
# 查看student表数据
select_student_data = "SELECT * FROM student"
cursor.execute(select_student_data)
students = cursor.fetchall()
for row in students:
print(f"Student ID: {row[0]}, Name: {row[1]}, Age: {row[2]}")
# 查看teacher表数据
select_teacher_data = "SELECT * FROM teacher"
cursor.execute(select_teacher_data)
teachers = cursor.fetchall()
for row in teachers:
print(f"Teacher ID: {row[0]}, Name: {row[1]}, Subject: {row[2]}")
```
注意:这只是一个基本的示例,实际生产环境中可能需要考虑更复杂的错误处理和安全性措施。此外,上述代码假设你已经在本地运行了一个MySQL服务器。如果没有,你需要先启动MySQL服务。
阅读全文