• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

pymysql 操作数据库

mysql 搞代码 4年前 (2022-01-09) 18次浏览 已收录 0个评论

一.简介

  pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同,但目前pymysql支持python3.x而后者不支持3.x版本

  其执行语句与sql源码相似

二.使用

1.安装

  pip install pymysql

2.使用操作

  先来一例完整的连接加基本的操作

import pymysql  # 创建连接conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')# 创建游标cursor = conn.cursor()  # 执行SQL,并返回收影响行数effect_row = cursor.execute("update hosts set host = '1.1.1.2'")  # 执行SQL,并返回受影响行数#effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))  # 执行SQL,并返回受影响行数#effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])    # 提交,不然无法保存新建或者修改的数据conn.commit()  # 关闭游标cursor.close()# 关闭连接conn.close()

向数据库插入数据,使用try语句,当出现异常是主动回滚

#!/usr/bin/python3import pymysql# 打开数据库连接db = pymysql.connect("localhost","testuser","test123","TESTDB" )# 使用cursor()方法获取操作游标 cursor = db.cursor()# SQL 插入语句sql = """INSERT INTO EMPLOYEE(FIRST_NAME,         LAST_NAME, AGE, SEX, INCOME)         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""try:   # 执行sql语句   cursor.execute(sql)   # 提交到数据库执行   db.commit()except:   # 如果发生错误则回滚   db.rollback()# 关闭数据库连接db.close()

3.向数据表中插入多条数据,使用executemany方法,在生产环境中插入多条数据 ,在后台中获取数据后,以列表的形式传入语句([('v1','v2'),('v3','v4')])

# 创建连接conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')# 创建游标cur = conn.cursor() if request.method == "POST":        title = request.POST.get("title")        title_en = request.POST.get("title_en")        content = request.POST.get("content")        content_en = request.POST.get("content_en")        notification_type =request.POST.get("notification_type").stri<b style="color:transparent">本文来源gao@!dai!ma.com搞$$代^@码!网!</b>p()        user_list = request.POST.get("user_list")        updated_datetime = datetime.now()        created_datetime = datetime.now()        values_list = []         for user in user_id_list:                temp = updated_datetime,created_datetime,title,title_en,content,content_en,notification_type,user['id']                values_list.append((temp))     try:          cur.executemany('''insert into app_notification(updated_datetime, created_datetime, title, title_en,                                  content, content_en, notification_type, is_read, recipient_id)                      values(%s, %s, %s, %s, %s, %s, %s, 0, %s)''',values_list)            conn.commit()            conn.close()         except Exception as err:        conn.rollback()        logging.error(err)        logging.error(traceback.format_exc())        conn.close()

# 获取最新自增ID

  new_id = cursor.lastrowid

4.数据库查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

fetchone(): 该方法获取下一个查询结果集。结果集是一个对象

fetchall(): 接收全部的返回结果行.

rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

import pymysql  conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')cursor = conn.cursor()cursor.execute("select * from hosts")  # 获取第一行数据row_1 = cursor.fetchone()  # 获取前n行数据# row_2 = cursor.fetchmany(3)# 获取所有数据# row_3 = cursor.fetchall()  conn.commit()cursor.close()conn.close()

注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:

cursor.scroll(1,mode='relative') # 相对当前位置移动

cursor.scroll(2,mode='absolute') # 相对绝对位置移动

5。fetch数据类型

  关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:

#!/usr/bin/env python# -*- coding:utf-8 -*-import pymysql  conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')  # 游标设置为字典类型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)r = cursor.execute("call p1()")  result = cursor.fetchone()  conn.commit()cursor.close()conn.close()

错误处理

DB API中定义了一些数据库操作的错误及异常,下表列出了这些错误和异常:


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:pymysql 操作数据库

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址