欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

django连接mysql

程序员文章站 2022-07-09 19:52:11
...

1.setting.py中修改

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'py_db',
        'USER': 'root',
        'PASSWORD': '12345',
        'HOST': '127.0.0.1',
        'POST': '3306'
    }
}

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tes3',
]

2.views.py

from django.shortcuts import render
from django.db import models
# Create your views here.

class Author(models.Model):
    id=models.AutoField(primary_key=True)
    name=models.CharField(max_length=50)

class Article(models.Model):
    id=models.AutoField(primary_key=True)
    content=models.CharField(max_length=100)

3.appname/init.py

import pymysql
pymysql.install_as_MySQLdb

4.安装好mysql和mysqlclient

5.建好一个数据库

django连接mysql

6.命令提示符中

C:\place\pycharm\untitled\PYC04\demo3>python manage.py makemigrations
Migrations for 'tes3':
  tes3\migrations\0001_initial.py
    - Create model Article
    - Create model Author

C:\place\pycharm\untitled\PYC04\demo3>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, tes3
Running migrations:
  Applying tes3.0001_initial... OK

7.打开数据库可看到

django连接mysql

8.可查询sql语句

C:\place\pycharm\untitled\PYC04\demo3>python manage.py sqlmigrate tes3 0001
BEGIN;
--
-- Create model Article
--
CREATE TABLE `tes3_article` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `content` varchar(100) NOT NULL);
--
-- Create model Author
--
CREATE TABLE `tes3_author` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(50) NOT NULL);
COMMIT;

9.可以看到生成的新文件

django连接mysql
每次更改要重新同步

—————————————————————————————————————————————————————

  • 一些报错:
C:\place\pycharm\untitled\PYC04\demo3>python manage.py migrate
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\place\python\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\place\python\lib\site-packages\django\core\management\__init__.py", line 357, in execute
    django.setup()
  File "C:\place\python\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\place\python\lib\site-packages\django\apps\registry.py", line 114, in populate
    app_config.import_models()
  File "C:\place\python\lib\site-packages\django\apps\config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\place\python\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\place\python\lib\site-packages\django\contrib\auth\models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\place\python\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\place\python\lib\site-packages\django\db\models\base.py", line 117, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\place\python\lib\site-packages\django\db\models\base.py", line 321, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\place\python\lib\site-packages\django\db\models\options.py", line 204, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\place\python\lib\site-packages\django\db\__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\place\python\lib\site-packages\django\db\utils.py", line 201, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\place\python\lib\site-packages\django\db\utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\place\python\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\place\python\lib\site-packages\django\db\backends\mysql\base.py", line 36, in <module>
    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

解决:
打开"C:\place\python\lib\site-packages\django\db\backends\mysql\base.py"这个文件,注释掉这两行
django连接mysql

C:\place\pycharm\untitled\PYC04\demo3>python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\place\python\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\place\python\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\place\python\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\place\python\lib\site-packages\django\core\management\base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:\place\python\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\place\python\lib\site-packages\django\core\management\commands\makemigrations.py", line 101, in handle
    loader.check_consistent_history(connection)
  File "C:\place\python\lib\site-packages\django\db\migrations\loader.py", line 283, in check_consistent_history
    applied = recorder.applied_migrations()
  File "C:\place\python\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations
    if self.has_table():
  File "C:\place\python\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table
    return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
  File "C:\place\python\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor
    return self._cursor()
  File "C:\place\python\lib\site-packages\django\db\backends\base\base.py", line 233, in _cursor
    self.ensure_connection()
  File "C:\place\python\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection
    self.connect()
  File "C:\place\python\lib\site-packages\django\db\backends\base\base.py", line 197, in connect
    self.init_connection_state()
  File "C:\place\python\lib\site-packages\django\db\backends\mysql\base.py", line 231, in init_connection_state
    if self.features.is_sql_auto_is_null_enabled:
  File "C:\place\python\lib\site-packages\django\utils\functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\place\python\lib\site-packages\django\db\backends\mysql\features.py", line 82, in is_sql_auto_is_null_enabled
    cursor.execute('SELECT @@SQL_AUTO_IS_NULL')
  File "C:\place\python\lib\site-packages\django\db\backends\utils.py", line 103, in execute
    sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  File "C:\place\python\lib\site-packages\django\db\backends\mysql\operations.py", line 146, in last_executed_query
    query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'

解决:
打开"C:\place\python\lib\site-packages\django\db\backends\mysql\operations.py"这个文件,注释掉这两行
django连接mysql