Python3 MySQL 使用pymysql 需先安装 pip3 install pymysql
一、python连接mysql数据库
import pymysql
# 打开数据库连接//ip 账号 密码
conn = pymysql.connect("*.*.*.*", "******", "******")
# 使用cursor()方法获取操作游标
cursor = conn.cursor()
sql_db = """CREATE DATABASE IF NOT EXISTS hardwareTestDb DEFAULT CHARSET utf8 COLLATE utf8_general_ci"""
cursor.execute(sql_db)
print('创建pythonBD数据库成功')
cursor.close()#先关闭游标
conn.close()#再关闭数据库连接
conn = pymysql.connect("*.*.*.*", "******", "******","hardwareTestDb")
sql_table="""CREATE TABLE IF NOT EXISTS userName(NAME VARCHAR(20),company VARCHAR(20),age INT)"""
cursor = conn.cursor()
cursor.execute(sql_table)
print('创建pythonTable成功')
cursor.close()#先关闭游标
conn.close()#再关闭数据库连接
二、Django配置MySQL数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'django', # 你要存储数据的库名,事先要创建之
'USER': 'django', # 数据库用户名
'PASSWORD': 'django@123', # 密码
'HOST': 'localhost', # 主机
'PORT': '3306', # 数据库使用的端口
}
}
多个数据库连接
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'hardwareTestDb',
'USER': '********',
'PASSWORD': '********',
'HOST': '**.**.**.**',
'PORT': '3306',
},
'mydb': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
>>> BookClass.newObj.using("mydb").all()
Terminal中执行数据库迁移命令
python manage.py makemigrations
python manage.py migrate
bug
问:
“import MySQLdb as DatabaseModuleNotFoundError: No module named 'MySQLdb'
”
答:
在站点的 init.py 文件中添加
import pymysql
pymysql.install_as_MySQLdb()
问:
“TypeError: __init__() takes 1 positional argument but 5 were given
”
答:
PyMySQL 版本支持 以下版本测试可以
pip install PyMySQL==0.10.1