国产午夜色司机在线观看,亚洲国产小视频在线观看,国产精品毛片一级久久,欧美高清vivoe,国产指交视频一区之二区,中文字幕在线码一区,18成禁人视频免费网站,影视中文综合国产,在线观看特色大片免费视频,午夜激情成人在线

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

  解釋:利用游標執(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()


<