1. 程式人生 > >python django建立資料庫表並連線mysql資料庫(附mysql 8.0.12安裝)

python django建立資料庫表並連線mysql資料庫(附mysql 8.0.12安裝)

先寫下mysql zip安裝方式,在環境變數中加入mysql/bin路徑,把zip解壓到C:\program files下,在最外層資料夾建立my-default.ini

寫入內容:

[mysqld] 

basedir=C:\Program Files\MySQL

datadir=C:\Program Files\MySQL\data

然後使用管理員許可權啟動CMD進入c:\program files\mysql\bin,

c:\Program Files\MySQL\bin>mysqld --initialize --user=mysql --console 

 (這個很關鍵)初始化會用到你寫的ini檔案,生成data檔案下面標註的紅色字一定要記下來,這個就是初始密碼(注意我這個還有個;),後面再改
2018-10-14T11:37:30.926791Z 0 [System] [MY-013169] [Server] c:\Program Files\MySQL\bin\mysqld.exe (mysqld 8.0.12) initializing of server in progress as process 3016
2018-10-14T11:37:34.342926Z 5 [Note] [MY-010454] [Server] A temporary password is generated for
[email protected]
: ;D3-yiQ02ubz
2018-10-14T11:37:35.774049Z 0 [System] [MY-013170] [Server] c:\Program Files\MySQL\bin\mysqld.exe (mysqld 8.0.12) initializing of server has completed  

c:\Program Files\MySQL\bin>mysqld install
Service successfully installed.

c:\Program Files\MySQL\bin>net start mysql


MySQL 服務正在啟動 .
MySQL 服務已經啟動成功。

c:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.12

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> alter user [email protected] IDENTIFIED BY '123456'
    -> ;
Query OK, 0 rows affected (0.02 sec)

下面講python django如何使用mysql

首先修改settings.py裡面資料庫配置內容,原來為sqlite3, 修改為mysql

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }
DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'app1',    #你的資料庫名稱

        'USER': 'root',   #你的資料庫使用者名稱

        'PASSWORD': '123456', #你的資料庫密碼

        'HOST': '', #你的資料庫主機,留空預設為localhost

        'PORT': '3306', #你的資料庫埠
    }
}

因為django預設不是mysql資料庫,需要在專案_ini_.py中加入下面的語句

import pymysql
pymysql.install_as_MySQLdb()

如果import pymysql沒法識別則在cmd中安裝,語句如下

c:\>pip install pymysql

models.py中建立class,,之後再連線資料庫建立表

from django.db import models

# Create your models here.
class myBook(models.Model):
    #book_id  varchar型別
    book_name = models.CharField(max_length=20)
    book_price = models.FloatField()
    pub_date=models.DateField()

terminal命令列中輸入下面兩行命令,建立成功!此時可以去資料查看錶是否建立成功

C:\Users\mayn\PycharmProjects\myORM>python manage.py makemigrations
Migrations for 'app1':
  app1\migrations\0001_initial.py
    - Create model myBook

C:\Users\mayn\PycharmProjects\myORM>python manage.py migrate