Django中直接執行SQL語句

2022-04-04 16:28:28 字數 2850 閱讀 4120

歡迎加入python學習*** 667279387

今天在django views.py看到同事寫的**裡面有段關於資料庫查詢的語句。因為涉及多個表的查詢,所以django 的models的查詢無法滿足需求,所以直接執行了sql語句。他是按照下面的方法實現的。

try:

connection = mysqldb.connect(host=sql_ip,

user=sql_user,

passwd=sql_passwd,

db=sql_db, charset='utf8')

cursor = connection.cursor()

cmd_query = query_data(request)

data_sort = sort_data(request)

cmd = "set session group_concat_max_len = 8000;"

cursor.execute(cmd)

......

看到這段**,感覺應該重複造了輪子,資料庫的鏈結應該交由django這個框架處理的。於是檢視了下官方文件。

django.db.connection 就是上面的同事寫的那個connection了。

後面的方法同他的一樣執行就是了。即執行

connection.cursor()

cursor.execute(sql, [params])

cursor.fetchone() or cursor.fetchall()

下面是乙個簡單的例子。

from django.db import connection

defmy_custom_sql

(self):

with connection.cursor() as cursor:

cursor.execute("update bar set foo = 1 where baz = %s", [self.baz])

cursor.execute("select foo from bar where baz = %s", [self.baz])

row = cursor.fetchone()

return row

如果你專案中有多個資料庫的話,django.db.connection也能很方便的選取資料庫。django.db.connections 是乙個類字典的結構,允許你使用資料庫別名獲取connection。

from django.db import connections

with connections['my_db_alias'].cursor() as cursor:

# your code here...

使用with作為上下文管理器:

with connection.cursor() as c:

c.execute(...)

和下面這段**等效

c = connection.cursor()

try:

c.execute(...)

finally:

c.close()

注意的問題:

如果你做了更新或者插入操作需要在**中使用 :transaction.commit_unless_managed() 來提交資料。或者使用事務裝飾器(例如 commit_on_success)來修飾檢視和提供事務控制資料提交。這樣就不用在**中呼叫transaction.commit_unless_managed()。但是,如果你不手動提交修改,你需要使用 transaction.set_dirty() 將事務標識為已髒。使用 django orm 對資料庫進行修改時,django 會自動呼叫 set_dirty() 。但如果你使用了原始 sql ,django 就無法獲得你的 sql 是否修改了資料。只有手動呼叫 set_dirty() 才能確保 django 知曉哪些修改必須被提交。

from django.db.transaction import commit_on_success

@commit_on_success

defmy_custom_sql_view

(request, value):

from django.db import connection, transaction

cursor = connection.cursor()

# data modifying operation

cursor.execute("update bar set foo = 1 where baz = %s", [value])

# since we modified data, mark the transaction as dirty

transaction.set_dirty()

# data retrieval operation. this doesn't dirty the transaction,

# so no call to set_dirty() is required.

cursor.execute("select foo from bar where baz = %s", [value])

row = cursor.fetchone()

#transaction.commit_unless_managed()

return render_to_response('template.html', )

如果不使用

參考文獻:

1、歡迎加入python學習*** 667279387

在EF中直接執行SQL命令

通過將objectcontext.connection轉換為entityconnection,再把 entityconnection.storeconnection轉換為sqlconnection。有了這個sqlconnection,我們再建立 sqlcommand便能順利執行sql命令了。例如 u...

DOS視窗中直接執行cmd命令執行sql檔案

有時我們會在沒有裝有相應資料庫的情況下我們還是要去執行資料庫語句 這時的資料庫就是在別的電腦上,我們只需知道他資料庫的ip位址,使用者名稱,密碼和所需用到的資料庫名即可。在dos下執行 cmd c osql s 127.0.0.1 u sa p 123 d test i e workspaces w...

Linux伺服器中直接執行sql檔案

mysql uroot p123456 h127 0.0 1 h,指定ip位址,預設為localhost u,指定使用者名稱 p,指定密碼 create database 資料庫名 show databases 顯示所有資料庫列表use 資料庫名 source usr local crazy fil...