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 root@localhost: ;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 root@localhost 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

猜你喜欢

转载自blog.csdn.net/java_raylu/article/details/83049480