1. 程式人生 > 其它 >django使用原生的sql以及ORM操作mysql

django使用原生的sql以及ORM操作mysql

在django專案中的setting配置資料庫

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'stu_manage',
        'USER': 'root',
        'PASSWORD': '1qaz2wsx',
        'HOST': 'localhost',
        'PORT': 3306
        # python manage.py inspectdb > app01/models.py
        # python manage.py makemigrations ,python manage.py migrate
    }
}

 

封裝一個原生sql語句操作資料庫的類方法

class SqlHelper(object):
    def __init__(self):
        # 讀取配置檔案
        self.connect()
    def connect(self):
        self.conn = pymysql.connect(host='127.0.0.1',
                               port=3306,
                               user='root',
                               passwd='1qaz2wsx',
                               db='stu_manage',
                               charset='utf8')
        # 建立遊標
        # 遊標設定為字典型別
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    def get_list(self, sql, args):
        # 執行SQL,返回值
        self.cursor.execute(sql, args)
        # 獲取資料
        result = self.cursor.fetchall()
        return result

    def get_one(self, sql, args):
        # 執行SQL,返回值
        self.cursor.execute(sql, args)
        # 獲取資料
        result = self.cursor.fetchone()
        return result

    def modify(self, sql, args):
        # 執行SQL,返回值
        self.cursor.execute(sql, args)
        # 提交資料
        self.conn.commit()

    def multiple_modify(self, sql, args):
        # self.cursor.executemany("insert into d(id name) values(%s, %s)", [(1,'alex'), (2, 'eric')])
        self.cursor.executemany(sql, args)
        self.conn.commit()

    def create(self, sql, args):
        # 執行SQL,返回值
        self.cursor.execute(sql, args)
        # 返回主鍵id
        last_row_id = self.cursor.lastrowid
        # 提交資料
        self.conn.commit()
        return last_row_id

    def close(self):
        self.cursor.close()
        self.conn.close()

# obj = SqlHelper()
# obj.connect()
# obj.multiple_modify()
# obj.close()

  

增刪改查