一、配置数据库
Django默认数据库为sqlite
若该项目要使用mysql数据库,需要更改配置
1、项目下setting.py中添加如下代码
import pymysql
pymysql.install_as_MySQLdb()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',# Add 'postgresql_psycopg2','mysql', 'sqlite3' or 'oracle'
'NAME': 'mydb', # Your db name, Or path to database file if using sqlite3
'USER':'root', # Your db user name, Not used with sqlite3
'PASSWORD':'mysql123', # Your db password, Not used with sqlite3
'HOST':'', # Your db host, set to empty string('') for default for localhost, Not used with sqlite3
'PORT':'3306', # Your db port, set to empty string('') for default, Not used with sqlite3
}
}
2、进行数据迁移
进入项目地址(与manage.py同级),执行如下命令
python38 manage.py makemigrations# 创建 迁移
python38 manage.py migrate# 执行 迁移
3、执行完毕后,可在mysql指定的数据库中看到已经完成迁移的数据表,至此,mysql数据库配置完成
C:\mysite001>python38 manage.py dbshell
mysql> use mydb
Database changed
mysql> show tables;
mysql> desc blog_BlogInfo;
在第一步之后一直报错
尝试了添加环境变量
尝试了修改my.ini,我路径下面没有,自己建了一个
[mysqld]
basedir ="C:\Program Files\MySQL\MySQL Server 8.0"
datadir ="C:\Program Files\MySQL\MySQL Server 8.0\data"
port=3306
server_id =10
character-set-server=gbk
character_set_filesystem=gbk
[client]
port=3306
default-character-set=gbk
[mysqld_safe]
timezone="CST"
[mysql]
default-character-set=utf8
尝试了安装pip3 install mysqlclient --user
尝试了修改python3.6/site-packages/django/db/backends/mysql/opetions.py
将decode改为encode,代码为:
def last_executed_query(self, cursor, sql, params):
# With MySQLdb, cursor objects have an (undocumented) "_executed"
# attribute where the exact query sent to the database is saved.
# See MySQLdb/cursors.py in the source distribution.
query = getattr(cursor, '_executed', None)
if query is not None:
query = query.encode(errors='replace')
return query
一直没解决,重启了下电脑,发现net start mysql又启动不了了,啊啊啊啊啊
但是python38 manage.py dbshell换了个错报:
ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (10061)
CommandError: "mysql --user=root --host=localhost --port=3306 POI_DB_Users" returned non-zero exit status 1.
把data删了,再按这个来一遍,net start mysql又能启动了:https://blog.csdn.net/qq_56572867/article/details/122560555
然后也按这个教程把密码改了,然后就好了。
查看mysql的端口号:
网友评论