pymysql 插入数据
时间: 2023-09-01 22:11:21 浏览: 95
插入数据可以使用 `INSERT INTO` 语句,具体操作步骤如下:
1. 导入 `pymysql` 模块:
```python
import pymysql
```
2. 连接数据库:
```python
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='password',
db='database_name',
charset='utf8mb4'
)
```
3. 获取游标:
```python
cursor = conn.cursor()
```
4. 编写 `INSERT INTO` 语句:
```python
sql = "INSERT INTO table_name (column1, column2, ...) VALUES (%s, %s, ...)"
```
5. 执行 SQL 语句:
```python
cursor.execute(sql, (value1, value2, ...))
```
6. 提交事务:
```python
conn.commit()
```
完整的代码示例:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='password',
db='database_name',
charset='utf8mb4'
)
# 获取游标
cursor = conn.cursor()
# 插入数据
sql = "INSERT INTO table_name (column1, column2, ...) VALUES (%s, %s, ...)"
cursor.execute(sql, (value1, value2, ...))
# 提交事务
conn.commit()
# 关闭游标和连接
cursor.close()
conn.close()
```
阅读全文