django使用mysql

来源:互联网 发布:java poi word 编辑:程序博客网 时间:2024/05/21 06:40

1. 按照django官网的文档https://docs.djangoproject.com/en/1.5/intro/tutorial01/  一步一步安装成功,修改好setting.py之后 ,执行

python manage.py syncdb

抛出如下异常

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb


2. google了一下相关的信息说是MySQL-python没装,yum install MySQL-python安装,提示本机已经有更新的版本,但执行python manage.py sycndb还是提示一样的错误。

在stackoverflow上看到一个问题:http://stackoverflow.com/questions/2952187/getting-error-loading-mysqldb-module-no-module-named-mysqldb-have-tried-pre

我本机没有pip命令,也没有研究它,执行上面文章说的命令:easy_install MySQL-python,提示我:

The required version of distribute (>=0.6.28) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U distribute'.

于是执行easy_install -U distribute,安装成功后,再次执行easy_install MySQL-python成功!


3 再次执行:

python manage.py syncdb

setting.py设置HOST为空时,提示:OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)")

但是查看mysql数据库,host+用户名+密码都没有问题。

注意到setting.py设置HOST那一行有注释:Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.

我的Host配的是127.0.0.1,意思好像是会通过TCP连接,如果为空会通过socket连接,于是改成127.0.0.1,再执行python manage.py syncdb,创建成功。

这里还要注意setting.py文件中:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'djangotest',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '127.0.0.1',        # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '4306',                      # Set to empty string for default.
    }
}

这里的'NAME'值填数据库的名字,数据库必须预先创建好,django不会为你创建数据库,在django documentation上也有说明。


原创粉丝点击