PyMysql模块是Python3中用于操作Mysql数据库的模块。
安装PyMysql
在Pycharm的Terminal中执行安装命令
pip install pymysql
创建连接对象
引入pymysql,使用connect方法创建数据库连接对象,参数是数据库的地址、用户名、密码、数据库名称。
import pymysql
conn = pymysql.connect(host="localhost",user="root",password="rootroot",database="baex")
创建游标对象
使用cursor方法创建游标对象
cursor = conn.cursor()
执行SQL
使用游标对象的execute方法执行SQL语句。
sql = "select * from sys_role"
cursor.execute(sql)
获取结果
游标对象,提供了三个获取结果的方法,fetchall、fetchone、fetchmany。
使用fetchall方法获取全部结果数据。
result = cursor.fetchall()
测试
运行代码,能看到在控制台输出了查询到的数据。
查询的结果是没有列名的,如果需要可以自定义字典,将列名和值以键值对的方式存储。
提交事务
如果是增删改操作必须使用数据库连接的commit方法提交事务,或者使用rollback进行事务回滚。
conn.commit()
conn.rollback()
释放资源
游标对象和数据库连接对象使用完毕后要进行释放,不然会一直占用数据库的资源。
cursor.close()
conn.close()
完整代码
import pymysql
conn = pymysql.connect(host="localhost",user="root",password="rootroot",database="baex")
cursor = conn.cursor()
sql = "select * from sys_role"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
cursor.close()
conn.close()