python django操作sqlite3

一,建立django项目

创立APP

django-admin startapp appname

注册app

python django操作sqlite3_第1张图片

打开model.py,添加表

from django.db import models

# Create your models here.

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    age = models.IntegerField()

5:admin后台注册表

修改app的admin.py文件:把models创建的表添加到admin后台中

from django.contrib import admin

# Register your models here.
from app import models
admin.site.register(models.UserInfo)

创建数据库db.sqlit3

venv\Scripts\python manage.py makemigrations
 F:\Anaconda\python manage.py makemigrations

将改动同步到数据库

venv\Scripts\python manage.py migrate
 F:\Anaconda\python manage.py migrate

二,创建用户

venv\Scripts\python manage.py createsuperuser
 F:\Anaconda\python manage.py createsuperuser

python django操作sqlite3_第2张图片

 然后可以后台登录http://127.0.0.1:8000/admin/对数据库进行管理

python django操作sqlite3_第3张图片

三,用py文件对表进行操作 

新建py文件

python django操作sqlite3_第4张图片

查询一个表里全部数据

#导入sqllite3模块
import sqlite3
# 1.硬盘上创建连接
con = sqlite3.connect("../db.sqlite3")
# 获取cursor对象
cur = con.cursor()
# 执行sql创建表

sql = 'select * from school_info'
try:
    cur.execute(sql)

    # 获取所有数据
    person_all = cur.fetchall()

    # 遍历
    for p in person_all:
        print(p)

except Exception as e:
    print(e)
    print('查询失败')
finally:
    # 关闭游标

通过改变sql的内容对数据库进行操作

查看全部表

导入sqllite3模块
import sqlite3
# 1.硬盘上创建连接
con = sqlite3.connect("../db.sqlite3")
# 获取cursor对象
cur = con.cursor()
# 执行sql创建表

#sql = 'select * from school_info'
try:
    #cur.execute(sql)
    cur.execute("select name from sqlite_master where type='table' order by name")
    #获取所有数据
    person_all = cur.fetchall()

    #遍历
    for p in person_all:
        print(p)
    # print (cur.fetchall())
except Exception as e:
    print(e)
    print('查询失败')
finally:
    # 关闭游标
    cur.close()
    # 关闭连接
    con.close()

你可能感兴趣的:(django,sqlite,数据库)