Django ORM 使用原生 SQL


使用原生sql的 方法 :

  1. raw

    # row方法:(摻雜着原生sql和orm來執行的操作)
    res = CookBook.objects.raw('select id as nid  from  epos_cookbook  where  id>%s', params=[1, ])
    print(res.columns) # ['nid']
    print(type(res)) # <class 'django.db.models.query.RawQuerySet'>
    
    # 在select里面查詢到的數據orm里面的要一一對應
    res = CookBook.objects.raw("select * from epos_cookbook")
    print(res)
    for i in res:
        print(i.create_date)
        print(i)
        
    res = CookBook.objects.raw('select * from epos_cookbook where id>%s', params=[1, ])
    # 后面可以加參數進來
    print(res)
    for i in res:
        # print(i.create_date)
        print(i)
    
  2. extra

    # (1,2) 必須兩個以上
    # res = CookBook.objects.extra(select={"aaa": "cook_type = 1"}, where=['id in (1,2)', ]).values()
    res = CookBook.objects.extra(select={"aaa": "cook_type = 1"}, where=['id in (1,2)', ])
    print(res)  # <QuerySet [<CookBook: 魚香肉絲>, <CookBook: 水煮魚>]>
    for r in res:
        print(r)
    
  3. connections (最原生)

    from django.db import connection, connections
    # 需要配置數據庫
    # cursor=connection['default'].cursor() 
    cursor = connection.cursor()  
    # 不傳參數的情況
    cursor.execute("""select  * from epos_cookbook""")
    
    # 為原生sql語句設置參數的情況
    # cursor.execute("""select  * from  epos_cookbook   where   id=%s""",[2,]) # 2 是 id
    # cursor.execute("""select  * from  api_userinfo   where   id=%s"""%1)
    
    # 防止注入攻擊
    cursor.execute("select  * from  epos_cookbook   where   id=%s", params=[1, ])
    # row=cursor.fetchone()
    # row=cursor.fetchmany()
    row = cursor.fetchall()  ##拿到全部的數據
    
    print(row)
    
    
    
    from django.db import connection
    
    cursor=connection.cursor()
    
    # 插入操作
    cursor.execute("insert into hello_author(name) values('錢鍾書')")
    
    # 更新操作
    cursor.execute("update hello_author set name='abc' where name='bcd'")
    
    # 刪除操作
    cursor.execute("delete from hello_author where name='abc'")
    
    # 查詢操作
    cursor.execute("select * from hello_author")
    
    raw=cursor.fetchone()  # 返回結果行游標直讀向前,讀取一條
    cursor.fetchall()  # 讀取所有
    
    

數據庫分離使用原生sql

from django.db import connection, connections
# cursor = connection.cursor()
cursor = connections['db2'].cursor()
cursor.execute("""SELECT * from app01_student """, )
row = cursor.fetchall()
print(row)
 ```


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM