Python pymysql cursor
时间: 2024-04-10 13:26:02 浏览: 167
带你彻底搞懂python操作mysql数据库(cursor游标讲解)
Python pymysql cursor是用于执行SQL语句并获取结果的对象[^1]。下面是两个关于Python pymysql cursor的例子:
1. 执行SQL语句并获取结果:
```python
import pymysql
# 创建连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', database='sys', charset='utf8')
# 获取游标
cursor = conn.cursor()
# 执行sql语句
cursor.execute("select version()")
# 获取结果集
res = cursor.fetchone()
print("当前数据库版本是 " + res)
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
```
2. 封装查询一条数据的方法:
```python
import pymysql
class DButil:
@classmethod
def select_getOne(cls, sql):
cursor = None
res = None
try:
# 创建连接
cls.conn = cls.__getConn()
# 获取游标
cursor = cls.conn.cursor()
# 执行sql语句
cursor.execute(sql)
# 获取结果集
res = cursor.fetchone()
except Exception as error:
print("查询错误", str(error))
finally:
cursor.close()
DButil.__getConn()
return res
```
阅读全文