久久久久久AV无码免费看大片,亚洲一区精品人人爽人人躁,国产成人片无码免费爱线观看,亚洲AV成人无码精品网站,为什么晚上搞的时候要盖被子

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

時(shí)間:2022-01-30 23:11:10 類型:python
字號(hào):    

  1.使用extra方法

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

  說明:依賴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('小強(qiáng)')")

  #更新

  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()


<