用Python语言,使用sql语句创建数据库,创建出可以通过键盘录入学生成绩的代码
时间: 2024-03-14 15:43:50 浏览: 133
好的,下面是代码:
```python
import mysql.connector
# 建立与数据库的连接
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password"
)
# 创建数据库
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE IF NOT EXISTS student")
# 连接到具体的数据库
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="student"
)
# 创建表
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE IF NOT EXISTS scores (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), score INT)")
# 插入数据
while True:
name = input("请输入学生姓名:")
if name == "exit":
break
score = input("请输入学生成绩:")
sql = "INSERT INTO scores (name, score) VALUES (%s, %s)"
val = (name, score)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "记录插入成功!")
```
这段代码会创建一个名为`student`的数据库,并在其中创建一个名为`scores`的表,其中包含`id`、`name`和`score`三个字段。然后,通过一个无限循环,不断从键盘获取输入,插入数据到`scores`表中,直到输入`exit`为止。每次插入成功后,会输出插入的记录数。
阅读全文
相关推荐
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)