Django连接MySQL数据库

1.修改settings.py 配置数据属性

DATABASES = {
default: {
ENGINE: django.db.backends.mysql,
NAME: fruitdb,
USER: root,
PASSWORD:hellosandy,
}
}

修改完后进入终端进入项目目录下执行python manage.py shell命令启动交互界面输入一下代码验证数据库配置是否成功。没报错则成功!

>>> from django.db import connection
>>> cursor = connection.cursor()

2.创建一个Django app

终端进入项目目录 执行 python manage.py startapp register生成目录文件如下:

products/
    __init__.py
    models.py
    tests.py
    views.py

3.编写models

from django.db import models

# Create your models here.
class Register(models.Model):
    nickname = models.CharField(max_length=30)
    email = models.CharField(max_length=50)
    password = models.CharField(max_length=30)

    def __unicode__(self):
        return "%s, %s, %s" % (self.nickname, self.email, self.password)

4.模型安装(修改settings.py)

INSTALLED_APPS = (
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles,
    register,
)

采用 python manage.py validate 检查模型的语法和逻辑是否正确。

没有错误则执行 python manage.py syncdb创建数据表。

SandymatoMacBook-Pro:fruitproject sandy$ python manage.py validate
0 errors found
SandymatoMacBook-Pro:fruitproject sandy$ python manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table register_register

现在你可以看到你的数据库除了生成了register_register 外还创建了其它好几个表,这些是django管理后台所需表暂不管。

 

Django连接MySQL数据库

上一篇:SQL基础 利用SELECT检索数据


下一篇:U3D笔记11:47 2016/11/30-15:15 2016/12/19