Django框架下連線Mysql資料庫

2021-08-19 21:15:46 字數 1816 閱讀 1630

1、找到settings.py檔案

2、新增如下**:

databases = 

}

3、在上面的基礎上,下面介紹兩種連線資料庫的具體方法

(1)使用models.py連線:

第一步:根據已存在的資料庫生成models.py檔案。進入cmd命令視窗,然後cd到你的專案中manage.py檔案所在目錄下,如

然後輸入python manage.py inspectdb,出現生成的**,然後複製到models.py檔案中即可。

首先要引入models.py檔案中相應的class。

# 

通過objects

這個模型管理器的

all()

獲得所以資料行,相當於

select * from tabel_name

# list=detail_data.objects.all()

# filter

相當於sql

中的where

,可設定條件過濾結果

result1 = detaildata.objects.filter(id

=oil_id)

#獲取分組

len=result1.__len__()

# 獲取單個物件

# response3=detail_data.objects.get_queryset(id='10051')

# 資料排序

# detail_data.objects.order_by('id')

# 上面的方法可以連鎖使用

# detail_data.objects.filter(id='10051').order_by('id')

# 獲取想要的結果

for

var in

result1:

(2)sql語句直接連線

首先引入pymysql庫或者mysqldb庫。**如下db=

pymysql.

connect

(server_ip(資料庫所在主機ip),database_username(使用者名稱),database_userpass(密碼),database_name(資料庫名))#獲取鏈結

cursor 

= db.

cursor

()#獲取游標

sqlstr

= "select * from table_name"

results

= cursor.

fetchall

()global

sj1#全域性變數

global

yl1for

row

in results

:sj1.

(row[0])

yl1.

(row[

1])

如果不是查詢操作,則可以使用

cursor = db.cursor()

try:

# 執行

sql語句

cursor.execute(sql_str)

# 提交到資料庫執行

db.commit()

except

:print("error: unable to fecth data")

python框架Django連線mysql

a.使用mysql資料庫首先需要安裝驅動程式 pip install pymysql b.在django的工程同名子目錄的 init py檔案中新增如下語句 import pymysql pymysql.install as mysqldb 作用是讓django的orm能以mysqldb的方式來呼叫...

在Django框架下,用redis實現購物車功能

先介紹一下本文中需要用到的資料庫模型類 goodssku,這個主要用於儲存商品,在這個模型類裡有price屬性 name屬性等。最終我們要實現的頁面效果是 購買商品頁面 購物車詳情頁面 總的思路是,因為購物車屬於頻繁被操作的物件,所以我們與之儲存在資料庫裡,不如儲存在記憶體裡。所以我們選擇redis...

Java集合框架(下)

上篇博文介紹了collection集合 這篇博文將介紹map集合。首先map和collection都是乙個介面,具體的實現都由下面的實現類實現功能。它們最大的區別就是collection是單列集合,map是雙列集合 泛型引數是乙個鍵 值對 map集合與set類似,主要有hashmap treemap...