pymysql 使用
时间: 2024-02-21 10:54:54 浏览: 120
pymysql是一个用于Python连接MySQL数据库的模块。它提供了一种简单和方便的方式来执行SQL查询和操作数据库。
以下是pymysql的使用示例:
- 连接到数据库: ```python import pymysql
打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='password', database='test')
创建游标对象
cursor = db.cursor()
执行SQL查询
cursor.execute("SELECT * FROM table_name")
获取查询结果
result = cursor.fetchall()
关闭游标和数据库连接
cursor.close() db.close()
2. 执行SQL查询:
```python
# 执行SELECT语句
cursor.execute("SELECT * FROM table_name")
# 获取查询结果
result = cursor.fetchall()
# 遍历结果
for row in result:
print(row)
- 执行SQL插入、更新和删除操作:
```python
执行INSERT语句
cursor.execute("INSERT INTO table_name (column1, column2) VALUES (%s, %s)", ('value1', 'value2'))
执行UPDATE语句
cursor.execute("UPDATE table_name SET column1 = %s WHERE column2 = %s", ('new_value', 'condition_value'))
执行DELETE语句
cursor.execute("DELETE FROM table_name WHERE column = %s", ('value',))
提交更改
db.commit()
请注意,以上示例仅为演示pymysql的基本用法,实际使用时需要根据具体情况进行适当的修改。
相关推荐

















