Django使用mysql数据库

Posted on 2011-10-19 00:01  仆本浪人  阅读(1484)  评论(2编辑  收藏  举报

为了使用mysql中的数据库,首先要下载mysql-python的模块

# apt-get install python-mysqldb

编辑配置文件(settings.py)

 1 DATABASES = {
2 'default': {
3 'ENGINE': 'django.db.backends.mysql', #设置为mysql数据库
4 'NAME': '', #mysql数据库名
5 'USER': '', #mysql用户名,留空则默认为当前linux用户名
6 'PASSWORD': '', #mysql密码
7 'HOST': '', #留空默认为localhost
8 'PORT': '', #留空默认为3306端口
9 }
10 }

django连接mysql

进入mysql新建一个数据库Blog,并且 GRANT ALL PRIVILEGES ON Blog.* TO lizzie@localhost IDENTIFIED BY '*******' WITH GRANT OPTION;

退出mysql

修改settings.py

DATABASES = {

    'default': {

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

        'NAME': 'mydb',                      

        'USER': 'root',                      

        'PASSWORD': '******',                  

        'HOST': '/var/run/mysqld/mysqld.sock',                     

        'PORT': '',                      

    }

}

保存后在python shell中测试是否连接正确

>>> from django.db import connection

>>> cursor = connection.cursor()