日韩精品欧美激情国产一区_中文无码精品一区二区三区在线_岛国毛片AV在线无码不卡_亞洲歐美日韓精品在線_使劲操好爽好粗视频在线播放_日韩一区欧美二区_八戒八戒网影院在线观看神马_亚洲怡红院在线色网_av无码不卡亚洲电影_国产麻豆媒体MDX

Django數(shù)據(jù)庫操作(執(zhí)行原生SQL的幾種方法)

時間:2022-01-30 23:11:10 類型:python
字號:    

  1.使用extra方法

  解釋:結(jié)果集修改器,一種提供額外查詢參數(shù)的機制

  說明:依賴model模型

  用在where后:

  News.objects.filter(id=1).extra(where=["title='生命的意義'"])

  用在select后

  News.objects.filter(id=1).extra(select={"count":"select count(*) from book"})

  2.使用raw方法

  解釋:執(zhí)行原始sql并返回模型

  說明:依賴model多用于查詢

  用法:

  student= Book.objects.raw("select * from student")

  for item in student:

  print(item.name)

  3.執(zhí)行自定義SQL

  解釋:利用游標(biāo)執(zhí)行

  導(dǎo)入:from django.db import connection

  說明:不依賴model

  用法:

  from django.db import connection

  cursor = connection.cursor()

  #插入

  cursor.execute("insert into student(name) values('小強')")

  #更新

  cursor.execute("updatestudent set name='小剛' where id=1")

  #刪除

  cursor.execute("delete from student where name='小王'")

  #查詢

  cursor.execute("select * from student")

  #返回一行

  raw = cursor.fetchone()

  print(raw)

  # #返回所有

  # cursor.fetchall()


<