pymysql插入数据
时间: 2023-10-23 21:27:59 浏览: 58
使用pymysql插入数据的步骤如下:
1. 连接数据库
```python
import pymysql
# 建立连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test', charset='utf8mb4')
```
2. 创建游标对象
```python
# 创建游标
cursor = conn.cursor()
```
3. 编写SQL语句
```python
# 编写SQL
sql = "INSERT INTO `users` (`name`, `age`, `gender`) VALUES (%s, %s, %s)"
```
4. 执行SQL语句
```python
# 执行SQL
cursor.execute(sql, ('Tom', 20, 'male'))
```
5. 提交事务
```python
# 提交事务
conn.commit()
```
6. 关闭游标和连接
```python
# 关闭游标和连接
cursor.close()
conn.close()
```
完整代码如下:
```python
import pymysql
# 建立连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test', charset='utf8mb4')
# 创建游标
cursor = conn.cursor()
# 编写SQL
sql = "INSERT INTO `users` (`name`, `age`, `gender`) VALUES (%s, %s, %s)"
# 执行SQL
cursor.execute(sql, ('Tom', 20, 'male'))
# 提交事务
conn.commit()
# 关闭游标和连接
cursor.close()
conn.close()
```
阅读全文