pymysql插入数据
时间: 2023-07-05 18:29:37 浏览: 81
使用 PyMySQL 模块可以很方便地向 MySQL 数据库中插入数据,具体步骤如下:
1. 导入 PyMySQL 模块:
```python
import pymysql
```
2. 建立数据库连接:
```python
conn = pymysql.connect(host='localhost', user='root', password='password', database='test', charset='utf8')
```
3. 获取游标:
```python
cursor = conn.cursor()
```
4. 编写 SQL 插入语句:
```python
sql = "INSERT INTO `students`(`name`, `age`, `gender`, `class`) VALUES (%s, %s, %s, %s)"
```
5. 执行 SQL 插入语句:
```python
cursor.execute(sql, ('John', 18, 'male', 'Class 1'))
```
6. 提交事务:
```python
conn.commit()
```
7. 关闭游标和数据库连接:
```python
cursor.close()
conn.close()
```
完整代码示例:
```python
import pymysql
# 建立数据库连接
conn = pymysql.connect(host='localhost', user='root', password='password', database='test', charset='utf8')
# 获取游标
cursor = conn.cursor()
# 编写 SQL 插入语句
sql = "INSERT INTO `students`(`name`, `age`, `gender`, `class`) VALUES (%s, %s, %s, %s)"
# 执行 SQL 插入语句
cursor.execute(sql, ('John', 18, 'male', 'Class 1'))
# 提交事务
conn.commit()
# 关闭游标和数据库连接
cursor.close()
conn.close()
```
阅读全文