Django連線資料庫

2021-09-02 01:35:56 字數 835 閱讀 6153

django作為python的主流web框架之一,擁有像dtl這樣優雅的模板語言,在普通html標籤的基礎上加入了像for標籤還有繼承等後台程式語言才有的東西。同時,django還可以十分便捷地實現資料庫等的連線,可以輕鬆地實現對資料庫的各種操作,使開發過程簡單容易。以下將用django連線mysql作為示例。

django連線資料庫非常簡便,只需要乙個驅動程式和對檔案的一點點設定。python中常用的mysql驅動程式有pymysql、mysqlclient等

pymysql安裝後需要在專案的settings.py和__init__.py檔案中進行設定. 

settings.py檔案:

databases = 

}

__init__.py檔案中:

import pymysql

pymysql.install_as_mysqldb()

做完這些,就可以在檢視函式中使用mysql資料庫了。

def index(request):

cursor = connection.cursor()

cursor.execute("insert into book(id,name,author) values(null ,'三國演義','羅貫中')")

cursor.execute("select * from book")

rows = cursor.fetchall()

for row in rows:

print(row)

return render(request, "index.html")

Django連線資料庫

python 2.7 mysql 5.7.17 mysql安裝 mysql服務無法開啟解決方案 django專案連線mysql pip install pymysql init py add the code into the file import pymysql pymysql.install ...

連線資料庫

2 documents 目錄就是我們可以用來寫入並儲存檔案得地方,一般可通過 nsarray paths nssearchpathfordirectoriesindomains nsdocumentdirectory,nsuserdomainmask,yes nsstring documentsdi...

連線資料庫

1 oracle8 8i 9i資料庫 thin模式 class.forname oracle.jdbc.driver.oracledriver newinstance string url jdbc oracle thin localhost 1521 orcl orcl為資料庫的sid strin...