如何在python中使用pymysql模块连接mysql数据库

分类:编程技术 时间:2024-02-20 15:23 浏览:0 评论:0
0
本文与大家分享如何使用python中的pymysql模块连接mysql数据库。小编觉得还是比较实用的,所以分享给大家学习一下。希望您读完本文后有所收获。没什么好说的。 ,下面就和小编一起来看看吧。

安装pymysql

pip install pymysql

2|0使用pymysql

2|1使用数据查询语句

查询数据fetchone()

从 pymysql import *conn = connect( host='127.0.0.1', port=3306, user='root',password='123456' , database='itcast', charset='utf8')# 创建游标 c = conn.cursor()# 执行sql语句 c.execute("select * from Student")# 查询一行数据 result = c.fetchone( )print(result)# 关闭游标 c.close()# 关闭数据库连接 conn.close()"""(1, '张三', 18, b'\x01')"""

查询多条数据fetchall()

从 pymysql 导入 *conn = connect(  主机='127.0.0.1', 端口=3306, 用户='root', 密码='123456', 数据库='itcast', 字符集=' utf8')# 创建游标 c = conn.cursor()# 执行sql语句 c.execute("select * from Student")# 查询多行数据 result = c.fetchall()for item in result: print(item) # 关闭游标 c.close()# 关闭数据库连接 conn.close( )"""(1, '张三', 18, b'\x01')(2, '李思', 19, b' \x00')(3, '王五', 20, b'\x01 ')"""

更改光标默认设置,返回值为字典

from pymysql import *conn = connect( 主机='127.0.0.1', 端口=3306, 用户='root', 密码='123456', 数据库='itcast' , charset='utf8')# 创建游标并设置操作为字典类型 c = conn.cursor(cursors.DictCursor)# 执行sql语句 c.execute("select * from Student")# 查询多行数据结果= c.fetchall()for item in result: print(item)# 关闭光标 c.close( )# 关闭数据库连接 conn.close()"""{'id': 1, '姓名': '张三', '年龄': 18, '性别': b'\x01'}{'id': 2, '姓名': '李思', '年龄': 19, '性别': b'\x00'}{'id': 3, '姓名': '王五', '年龄': 20, '性别' : b'\x01'}"""

返回一条数据时也是如此。根据个人需要返回字典或元组。

2|2使用数据操作语句

增删改查语句的操作其实是一样的。就写一个作为例子吧。

from pymysql import *conn = connect( 主机='127.0.0.1', 端口=3306, 用户='root', 密码='123456', 数据库=' itcast', charset='utf8')# 创建游标 c = conn.cursor()# 执行sql语句 c.execute("插入学生(姓名,年龄,性别)值(%s,%s,%s) )",("小二",28,1))# 提交事务 conn.commit()# 关闭游标 c.close()# 关闭数据库连接 conn.close()

与查询不同语句中,必须使用commit()来提交事务,否则操作将无效。

3|0编写数据库连接类

普通版

MysqlHelper.py

from pymysql import connect,cursorsclass MysqlHelper: def __init__(self, host="127.0.0.1", user="root",password="123456",database="itcast" , charset='utf8', 端口=3306): self.host = 主机 self.port = 端口 self.user = 用户 self.password = 密码 self.database = 数据库 self.charset = 字符集 self._conn = 无 self._cursor = None def _ open( self): # print("连接已打开") self._conn = connect(host=self.host, port=self.port, user=self.user, password=self.password,  database= self.database, charset=self.charset) self._cursor = self._conn.cursor(cursors.DictCursor) def _close(self): # print("连接已关闭") self._cursor.close() self ._conn .close() def one(self, sql, params=None): 结果: tuple = None 尝试: self._open() self._cursor.execute(sql, params) result = self._cursor.fetchone() except Exception as e: print(e) finally: self._close() returnresult def all(self, sql, params=None): result: tuple = None try: self._open() self._cursor.execute(sql, params) result = self._cursor.fetchall() except Exception as e: print (e) 最后: self._close() 返回结果 def exe(self, sql, params=None): try: self._open() self._cursor. execute(sql, params) self._conn.commit() except Exception as e: print(e) finally:   self._close()

该类封装了 fetchone、fetchall 和execute,无需打开和关闭数据库连接以及游标的打开和关闭。
下面的代码是调用该类的一个小例子:

from MysqlHelper import *mysqlhelper = MysqlHelper()ret = mysqlhelper.all("select * from学生")for item in ret: print(item)"""{'id': 1, '姓名': '张三', '年龄': 18, '性别': b'\x01'}{'id ' : 2, '姓名': '李思', '年龄': 19, '性别': b'\x00'}{'id': 3, '姓名': '王五', '年龄': 20 , '性别': b'\x01'}{'id': 5, '姓名': '小二', '年龄': 28, '性别': b'\x01'}{'id': 6, '姓名': '娃哈哈', '年龄': 28, '性别': b'\x01'}{' id': 7, '姓名': '娃哈哈', '年龄': 28, '性别': b'\x01'}"""上下文管理器版本 mysql_with.pyfrom pymysql import connect,cursorsclass DB: def __init__(self, host='localhost', port=3306, db='itcast', user='root', passwd='1234 56', charset='utf8'): # 建立连接 self.conn = connect( host=host, port=port, db=db,   user=user, passwd=passwd, charset=charset) #创建游标,并将操作设置为字典类型 self.cur = self.conn.cursor(cursor=cursors.DictCursor) def __enter__( self): #返回游标 return self .cur def __exit__(self, exc_type, exc_val, exc_tb): # 提交数据库并执行 self.conn.commit() # 关闭游标 self.cur.close() # 关闭游标数据库连接 self.conn.close()

使用方法:

from mysql_with import DBwith DB() as db: db.execute("从学生中选择 *") ret = db.fetchone() print(ret)"""{'id': 1, 'name': '张三', '年龄': 18, '性别': b'\x01'}"""

上面是如何使用python中的pymysql模块连接mysql数据库,小编认为有些知识点在我们日常工作中可能会看到或者用到,希望大家通过本文能够学到更多的知识,更多详情请关注行业资讯频道。

1. 本站所有资源来源于用户上传或网络,仅作为参考研究使用,如有侵权请邮件联系站长!
2. 本站积分货币获取途径以及用途的解读,想在本站混的好,请务必认真阅读!
3. 本站强烈打击盗版/破解等有损他人权益和违法作为,请各位会员支持正版!
4. 编程技术 > 如何在python中使用pymysql模块连接mysql数据库

用户评论