方法一:直接在models里连接mysql数据库,用sql语言操作
python2的代码:
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()
#创建数据表
#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
#插入一条数据
#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
#修改查询条件的数据
#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
#删除查询条件的数据
#cur.execute("delete from student where age='9'")
cur.close()
conn.commit()
conn.close()
python3的代码:
# coding=utf-8
import pymysql
pymysql.install_as_MySQLdb()
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
passwd='root',
db='test',
)
cur = conn.cursor()
# 创建数据表
cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
# 插入一条数据
# cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
# 修改查询条件的数据
# cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
# 删除查询条件的数据
# cur.execute("delete from student where age='9'")
cur.close()
conn.commit()
conn.close()
方法二:利用pymysql模块操作
前提:安装pymysql模块,在mysql数据库中先建立相应表
settings.py文件里
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql',
'HOST':'127.0.0.1',
#'PORT':'3306',
'USER':'root',
'PASSWORD':'123456',
}
}
对应app下_init_.py文件
import pymysql
pymysql.install_as_MySQLdb()
建立模型
from django.db import models
# Create your models here.
class user1(models.Model):
user=models.CharField(max_length=32)
pwd=models.CharField(max_length=32)
#user1为表名,user为表user1下相应字段名
页面调用
from django.shortcuts import render
from App01 import models#相应app下导入models.py文件
# Create your views here.
def get_pro_a(request):
msg=models.user1.objects.filter().first()
return render(request,'GetProA.html')
建立模型,和页面调用的方法同sqlite3的方式
如何用pycharm查看mysql里的数据库
右侧有个database,点开后左上角有个“+”符号,选择Data Source-Mysql
Host处填写服务器名,Database处填写表名star,User处填写该表的登录用户名,Password处填写该表的密码
附加1:mysql表里输入内容时出现1366错误
解决:文字字段类型不支持中文,默认是瑞典语(一下为gbk示例)
#ALTER TABLE 表格名 CONVERT TO CHARACTER SET gbk COLLATE gbk_chinese_ci
ALTER TABLE 'catalogue_star_pro_a' CONVERT TO CHARACTER SET latin1_swedish_ci COLLATE gbk_chinese_ci
附加2:python里打印某张表的字段名称
# coding=utf-8
import pymysql
pymysql.install_as_MySQLdb()
conn = pymysql.connect(
host='127.0.0.1',
# port=3306,
user='root',
passwd='123456',
db='star',
)
cur = conn.cursor()
Sql = "select * from star_pro_a"
cur.execute(Sql)
print('打印所有数据:',cur.description)
result = cur.fetchall()
data_dict=[]
for field in cur.description:
data_dict.append(field[0])
print('打印字段名:',data_dict)
问题:无论怎么设置mysql的编码为utf-8,用python对读取数据后的内容始终是乱码?
def get_pro_a(request):
msg = models.pro_a.objects.filter(id='1').first()
print(msg)
# 转成json数据格式
msgJson = json.dumps(dict([(attr, getattr(msg, attr)) for attr in [f.name for f in msg._meta.fields]]), ensure_ascii=False)#重点在dumps的时候要添加ensure_ascii=False这句,出现的就是中文了
print(msgJson)
return HttpResponse(msgJson)
ensure_ascii=False,这个相当重要
对于queryset格式的数据转为json格式
from django.core import serializers
def get_pro_a(request):
msgJson=serializers.serialize("json", models.a.objects.all(), ensure_ascii=False)
return HttpResponse(msgJson)