zoukankan      html  css  js  c++  java
  • django中使用原生的sql查询实例

    在app文件夹下创建database_operations.py文件,写如下内容:
    import pymysql
    from 项目名.settings import DATABASES
    
    
    class Database_operat(object):
        def __init__(self, database=DATABASES, database_name='default'):
            database_information = database[database_name]
            try:
                self.db = pymysql.connect(host=database_information['HOST'], user=database_information['USER'], port=database_information['PORT'],
                                          password=database_information['PASSWORD'], db=database_information['NAME'])
                self.cur = self.db.cursor()
            except pymysql.err.OperationalError as e:
                print(e)
                print("连接数据库失败")
                return
    
        #查全部数据
        def search_all(self, sql):
            data= ''
            try:
                self.cur.execute(sql)
                self.db.commit()
                data = self.cur.fetchall()
                print(data)
                data =[i[0] for i in data]
                print(data)
                # data =list(data)
            except pymysql.err.ProgrammingError as e:
                print(e)
                print("查询失败")
            except pymysql.err.InternalError as e :
                print(e)
                print("查询失败")
            finally:
                self.db.close()
            if data:
                return data
            else:
                data = []
                return data
        def close(self):
            self.db.close()
            return



    在views文件中可以这样使用:
    from .database_operations import *
    
    # 动态加载5个相似的批次号
    def search_batch(request):
        db = Database_operat()
        batch = request.GET.get('batch')
        batch = batch + '%'
        batch_like_sql = "SELECT batch FROM batch_comparison WHERE batch  LIKE '%s' LIMIT 0,5;" % batch
        batch_list = db.search_all(batch_like_sql)
        msg = json.dumps(batch_list)
        return HttpResponse(msg)
  • 相关阅读:
    电子邮件为什么要编码以及产生乱码的原因?
    UTF8国际通用为什么还要用GBK?
    python 调用shell命令的方法
    script —— 终端里的记录器
    IP数据报是如何在网络中转发的?
    网际协议:无连接数据报交付(IPv4)
    fork与vfork
    strlen与sizeof有什么区别?
    网络地址到物理地址的映射(ARP)
    分类的因特网地址
  • 原文地址:https://www.cnblogs.com/xshan/p/11792083.html
Copyright © 2011-2022 走看看