pymysql 操做数据库

一.简介 python

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

  其执行语句与sql源码类似sql

二.使用数据库

1.安装python3.x

   pip install pymysqlapp

2.使用操做fetch

  先来一例完整的链接加基本的操做spa

import pymysql
  
# 建立链接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
#第二种建立链接方式
#链接配置信息 
config = { 
    'host':'127.0.0.1', 
    'port':3306, 
    'user':'root', 
    'password':'123', 
    'db':'t1', 
    'charset':'utf8mb4',         
    'cursorclass':pymysql.cursors.DictCursor, 
} 
# 建立链接 (2)
connection = pymysql.connect(**config)

# 建立游标
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语句,当出现异常是主动回滚code

#!/usr/bin/python3

import 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')])orm

# 建立链接
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").strip()
        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中定义了一些数据库操做的错误及异常,下表列出了这些错误和异常:

异常 描述
Warning 当有严重警告时触发,例如插入数据是被截断等等。必须是 StandardError 的子类。
Error 警告之外全部其余错误类。必须是 StandardError 的子类。
InterfaceError 当有数据库接口模块自己的错误(而不是数据库的错误)发生时触发。 必须是Error的子类。
DatabaseError 和数据库有关的错误发生时触发。 必须是Error的子类。
DataError 当有数据处理时的错误发生时触发,例如:除零错误,数据超范围等等。 必须是DatabaseError的子类。
OperationalError 指非用户控制的,而是操做数据库时发生的错误。例如:链接意外断开、 数据库名未找到、事务处理失败、内存分配错误等等操做数据库是发生的错误。 必须是DatabaseError的子类。
IntegrityError 完整性相关的错误,例如外键检查失败等。必须是DatabaseError子类。
InternalError 数据库的内部错误,例如游标(cursor)失效了、事务同步失败等等。 必须是DatabaseError子类。
ProgrammingError 程序错误,例如数据表(table)没找到或已存在、SQL语句语法错误、 参数数量错误等等。必须是DatabaseError的子类。
相关文章
相关标签/搜索