pymysql 增加数据
时间: 2023-10-23 14:15:07 浏览: 81
使用 PyMySQL 模块可以方便地向 MySQL 数据库中增加数据。下面是一个简单的示例:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test')
# 创建游标对象
cursor = conn.cursor()
# 执行 SQL 语句
sql = "INSERT INTO student(name, age, gender) VALUES (%s, %s, %s)"
data = ('Tom', 20, 'male')
cursor.execute(sql, data)
# 提交事务
conn.commit()
# 关闭游标和连接
cursor.close()
conn.close()
```
在上述代码中,首先使用 `pymysql.connect()` 方法连接到 MySQL 数据库。然后,使用 `conn.cursor()` 方法创建游标对象。接着,使用 `cursor.execute()` 方法执行 SQL 语句,并传入参数值。最后,使用 `conn.commit()` 方法提交事务,并使用 `cursor.close()` 和 `conn.close()` 方法关闭游标和连接。
相关问题
pymysql增加单条数据
在Python中,pymysql是一个流行的MySQL数据库连接库。如果你想要使用它来向数据库中插入一条新数据,可以按照以下步骤操作:
```python
import pymysql
# 连接到数据库
db = pymysql.connect(host='your_host', user='your_username', password='your_password', database='your_database')
try:
# 创建一个游标对象
cursor = db.cursor()
# 定义SQL插入语句(假设你有一个名为users的表,字段有id, name, email)
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
# 准备要插入的数据,这里是元组格式
data = ("John Doe", "john.doe@example.com")
# 执行插入操作
cursor.execute(sql, data)
# 提交事务
db.commit()
print("Data inserted successfully")
except Exception as e:
# 如果发生错误,回滚事务
db.rollback()
print(f"Error occurred: {e}")
finally:
# 关闭连接
db.close()
```
这里的关键部分是`cursor.execute()`和`db.commit()`, 其中`execute()`用于执行SQL插入语句,`commit()`用来保存到数据库。
pymysql如何进行增加和删除数据
pymysql是一个Python MySQL数据库连接库,允许你在Python程序中操作MySQL数据库。以下是使用pymysql进行数据增加(插入)和删除的基本示例:
**增加数据(插入)**:
```python
import pymysql
# 连接到MySQL服务器
conn = pymysql.connect(
host='your_host',
user='your_username',
password='your_password',
database='your_database'
)
# 创建一个游标对象
cursor = conn.cursor()
# 插入数据的SQL语句
sql = """
INSERT INTO your_table (column1, column2, ...)
VALUES (%s, %s, ...)
"""
# 准备要插入的数据
data = ('value1', 'value2', ...)
try:
# 执行插入操作
cursor.execute(sql, data)
# 提交到数据库
conn.commit()
print(f"Data inserted successfully with ID {cursor.lastrowid}")
except Exception as e:
# 如果发生错误,回滚事务
conn.rollback()
print(f"Error occurred: {e}")
# 关闭游标和连接
cursor.close()
conn.close()
```
**删除数据(删除记录)**:
```python
# 更新SQL语句为删除操作
sql_delete = "DELETE FROM your_table WHERE some_condition"
try:
cursor.execute(sql_delete)
conn.commit()
print("Record deleted successfully")
except Exception as e:
conn.rollback()
print(f"Error occurred: {e}")
cursor.close()
conn.close()
```
这里`some_condition`应替换为你实际的删除条件。
阅读全文
相关推荐
















