Python接入mysql數據庫

方法一:直接在models裏鏈接mysql數據庫,用sql語言操做

python2的代碼:html

#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的代碼:python

# 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數據庫中先創建相應表mysql

settings.py文件裏sql

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()

創建模型django

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下相應字段名

頁面調用json

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裏的數據庫app

 

右側有個database,點開後左上角有個「+」符號,選擇Data Source-Mysqlfetch

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)
相關文章
相關標籤/搜索