Django数据库操作的注意事项《特别篇》!

数据库查询操作,一般使用生sql和模型对象,两种方式!

模型操作使用一般不会有太大的问题,

但是使用原生sql(pymysql)时有可能会遇到数据库查询周期性或者连续性失败的情况:

import pymysql

from allinone.settings import BASE_DIR


class Mysqls(object):
    def __init__(self):
        # 读取配置文件
        self.connect()

    def connect(self):
        try:
            self.connection = pymysql.connect(host="192.168.0.105", user="root", password="123456",
                                              database="allinones")
            self.cursor = self.connection.cursor()
        except Exception as e:
            print(e)
            # kill()

    # 获取所以数据
    def get_all(self, sql):
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()
        except:
            self.connection()
            self.cursor.execute(sql)
            return self.cursor.fetchall()
  def get_close(self):
self.cursor.close()


猜测引起的原因,可能为数据库引擎有表级锁或者行级锁的原因,与模型对象查询时出现冲突,又或者与数据库链接过多,没有关闭。

posted @ 2021-05-31 10:14  爱吃萝卜爱吃兔  阅读(85)  评论(0编辑  收藏  举报