天天看點

django 資料庫使用(sqlite3和mysql)

一、sqlite3 使用
1、import sqlite3 确認系統中是否安裝
2、進入目前項目目錄,cmd後運作python,進入指令行模式
3、import sqlite3,
   sqlite3.connect('{path\name.db}') #大括号内表示自定義,真實情況沒有大括号
4、修改settings.py檔案
   DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': {path\name.db}',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
5、進入資料庫檔案界面,運作python manage.py shell
   from django.db import connection
   cur = connection.cursor()
   如果沒報錯,則表示配置成功
6、修改models.py檔案,配置自己的表
   例如:
    from django.db import models
    from django.contrib import admin
    
    # Create your models here.
    class BlogPost(models.Model):
    	title = models.CharField(max_length = 150)
    	body  = models.TextField()
    	timestamp = models.DateTimeField()
    	class Meta:
    		ordering = ['-timestamp']
7、建立資料庫内容
   python manage.py syncdb
   根據提示輸入,表示連接配接成功
注:以上隻表示對資料庫的建立,連接配接和使用,不包含其它内容。

二、mysql
1、确認安裝mysql資料庫
2、在mysql中建立資料庫 指令模式下可以使用
   CREATE DATABASE {name} DEFAULT CHARSET=utf8;
3、修改settings.py檔案
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': '{name}',
            'USER': '{username}',
            'PASSWORD': '{password}',
            'HOST':'localhost', #ip
            'PORT':'3306',
        }
    }
4、修改models.py檔案,配置自己的表
   例如:
    from django.db import models
    from django.contrib import admin
    
    # Create your models here.
    class BlogPost(models.Model):
    	title = models.CharField(max_length = 150)
    	body  = models.TextField()
    	timestamp = models.DateTimeField()
    	class Meta:
    		ordering = ['-timestamp']
5、建立資料庫内容
   python manage.py syncdb
   根據提示輸入,表示連接配接成功                

版權聲明:本文為CSDN部落客「weixin_34067102」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_34067102/article/details/92154487