[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
一、前言
这段时间在玩Flask Web,发现用Flask Shell去操作SQLite还是比较方便的。今天简单地介绍一下。
二、SQLite
SQLite是一种嵌入式数据库,它的数据库就是一个文件,处理速度快,经常被集成在各种应用程序中,在IOS和Android开发中会用SQLite做为客户端缓存数据使用。在Android中继承SQLiteOpenHelper类去实现对SQLite的操作,这里我们不具体讲了,Android现在除了大厂外小公司基本上很少开发Android原生应用了。SQLite支持三种线程模型单线程、多线程、以及串行这个可以代码中配置,单线程模型时并发使用时会出问题,多线程模型时一个数据库连接不被多个线程同时使用就是安全的,串行会启用所有锁是线程安全的。
我们先在Python交互模式下操作SQLite。
创建表并插入一条数据
注:因为python3内置了sqlite3,直接导入sqlite驱动,然后创建连接,打开游标即可创建表及写增删改查SQL.会在当前目录下生成一个test.db文件,你可以用DBeaver数据库管理工具创建到该文件的连接,打开后与打开MySQL差不多,可以写常规的SQL语句去维护。
查询数据
三、Flask Shell
dbtest.py
配置环境export FLASK_APP=dbtest.py
SQLAlchemy是Python的一种ORM框架,通过定义模型对象,然后进入Flask
Shell中执行db.create_all()能够根据模型直接创建所有表,drop_all()删除所有表。
然后导入用户及角色对象,通过交互命令提交数据。
打开data.sqlite,数据已经写入数据库。