Python3和Django如何支援MySQL和MariaDB資料庫

來源:互聯網
上載者:User

標籤:python3   mysql   

原文地址:http://www.server110.com/mariadb/201404/10020.html

首先,[email protected] 中預設的引擎為 django.db.backends.mysql 。但是在Python3中如果這樣寫的話,會發現 django.db.backends.mysql 依賴 MySQLdb[5] ,而 MySQLdb 又不相容 Python3 於是要找一種新的方式來繼續使用MySQL。

首先據MySQL文檔[3]說,自從MySQL Connector/Python 1.1.1 開始,引入了 mysql.connector.django ,可直接作為 Django 的資料庫引擎使用,但是我試了1.1.2和1.1.3後發現,根本不是那麼回事[4]。

後來,發現了 PyMySQL[1] ,支援Python3 ,google後知道如何與 Django 結合使用[2],答案如下:

首先,安裝PyMySQL

for Windows

for Fedora


pip-python3 install PyMySQL


pip-python3 install PyMySQL 

然後,在 Django 網站的 __init__.py 檔案中添加如下兩行:


import pymysql

pymysql.install_as_MySQLdb()


import pymysql

 

pymysql.install_as_MySQLdb() 

最後是資料庫的配置(在settings.py)


DATABASES = {
    ‘default‘: {
        ‘ENGINE‘: ‘django.db.backends.mysql‘, #資料庫引擎
        ‘NAME‘: ‘test‘,                       #資料庫名
        ‘USER‘: ‘root‘,                       #使用者名稱
        ‘PASSWORD‘: ‘root‘,                   #密碼
        ‘HOST‘: ‘‘,                           #資料庫主機,預設為localhost
        ‘PORT‘: ‘‘,                           #資料庫連接埠,MySQL預設為3306
        ‘OPTIONS‘: {
            ‘autocommit‘: True,
        },
    }
}


DATABASES = {

    ‘default‘: {

        ‘ENGINE‘: ‘django.db.backends.mysql‘, #資料庫引擎

        ‘NAME‘: ‘test‘,                       #資料庫名

        ‘USER‘: ‘root‘,                       #使用者名稱

        ‘PASSWORD‘: ‘root‘,                   #密碼

        ‘HOST‘: ‘‘,                           #資料庫主機,預設為localhost

        ‘PORT‘: ‘‘,                           #資料庫連接埠,MySQL預設為3306 

        ‘OPTIONS‘: {

            ‘autocommit‘: True,

        },

    }

}

然後同步資料庫:

for Windows

for Fedora

OK, It works!



Python3和Django如何支援MySQL和MariaDB資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.