sqlite3 数据库

目录

一、安装

二、数据类型

存储类

Date 与 Time 数据类型

三、命令

四、Python 使用


一、安装

SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是在世界上最广泛部署的 SQL 数据库引擎。SQLite 源代码不受版权限制

官方下载地址: SQLite Download Page

windows 下载如下两个文件,解压到一个文件夹内,配置环境变量后 命令行使用查看安装情况:sqlite3 --version

linux  安装如下安装包

二、数据类型

存储类

存储类描述
NULL值是一个 NULL 值。
INTEGER值是一个带符号的整数,根据值的大小存储在 1、2、3、4、6 或 8 字节中。
REAL值是一个浮点值,存储为 8 字节的 IEEE 浮点数字。
TEXT值是一个文本字符串,使用数据库编码(UTF-8、UTF-16BE 或 UTF-16LE)存储。
BLOB值是一个 blob 数据,完全根据它的输入存储。

Date 与 Time 数据类型

SQLite 没有一个单独的用于存储日期和/或时间的存储类,但 SQLite 能够把日期和时间存储为 TEXT、REAL 或 INTEGER 值。

存储类日期格式
TEXT格式为 "YYYY-MM-DD HH:MM:SS.SSS" 的日期。
REAL从公元前 4714 年 11 月 24 日格林尼治时间的正午开始算起的天数。
INTEGER从 1970-01-01 00:00:00 UTC 算起的秒数。
序号函数实例
1date(timestring, modifier, modifier, ...)以 YYYY-MM-DD 格式返回日期。
2time(timestring, modifier, modifier, ...)以 HH:MM:SS 格式返回时间。
3datetime(timestring, modifier, modifier, ...)以 YYYY-MM-DD HH:MM:SS 格式返回。
4julianday(timestring, modifier, modifier, ...)这将返回从格林尼治时间的公元前 4714 年 11 月 24 日正午算起的天数。
5strftime(format, timestring, modifier, modifier, ...)这将根据第一个参数指定的格式字符串返回格式化的日期。具体格式见下边讲解。

三、命令

注意:命令前面的点 .

创建数据库文件:    .open databasename.db
退出:    .quit
查看当前数据库:    .databases
查看当前表名:    .tables
查看表的创建语句:    .schema tablename
删除表:    drop table tablename;
格式化显示select结果:    .header on        .mode column

# 创建表
CREATE TABLE IF NOT EXISTS "users" (id integer primary key autoincrement not null, env int, phone text, code text, kkuserid text, token text, update_time datetime default(datetime('now', 'localtime')));

# 插入数据
insert into users (name, env) select name, env from users_log;
insert into users (name, env) values ("张三", "测试");

# 更新数据
update users set name="李四" where env="测试";

# 删除数据
delete from users where name="李四";

# 删除表
drop table if exists users;

# 修改表名
alter table users rename to users_back;

四、Python 使用

1、创建链接

#!/usr/bin/python

import sqlite3
conn = sqlite3.connect('test.db')  # 没有这个库的话会新建库
print(conn)

2、创建游标

connection.cursor([cursorClass])

3、执行sql

cursor.execute(sql [, optional parameters])

4、提交

connection.commit()

5、回滚

connection.rollback()

6、关闭链接

connection.close()

7、获取查询结果的一行

cursor.fetchone()

8、获取查询结果的所有行

cursor.fetchall()

9、demo

import sqlite3
# 创建链接 本地没有此数据库的时候会自动创建数据库
conn = sqlite3.connect(database="activitys.db")
c = conn.cursor()

# 查询
# res = c.execute("select * from users;")
# print(res.fetchall())

# 插入数据
# res = c.execute("insert into test_01 (name, age) values('王五', 20);")
# conn.commit()

# 新建表
# c.execute("create table test_01"
#           "(id INTEGER primary key autoincrement not null,"
#           "name text not null,"
#           "age int not null,"
#           "time datetime default(datatime('now', 'localtime')));")
# 更新字段数值
# res = c.execute("update test_01 set name='lala' where name ='王五' and id=4;")

# 删除列
# res = c.execute("delete from test_01 where name ='lala';")
conn.commit()
print(c.fetchall())
conn.close()
#! /usr/bin/python3
# -*- coding: utf-8 -*-
import sqlite3


class Sqlite3Util:
    def __init__(self, sqlite3_db_file):
        # 创建链接 本地没有此数据库的时候会自动创建数据库
        self.conn = sqlite3.connect(database=sqlite3_db_file)
        self.cursor = self.conn.cursor()

    def select(self, sql):
        res = self.cursor.execute(sql)
        return res.fetchall()

    def insert(self, sql):
        res = self.cursor.execute(sql)
        try:
            self.conn.commit()
        except:
            self.conn.rollback()
            return Exception
        return res

    def update(self, sql):
        res = self.cursor.execute(sql)
        try:
            self.conn.commit()
        except:
            self.conn.rollback()
            return Exception
        return res

    def delete(self, sql):
        res = self.cursor.execute(sql)
        try:
            self.conn.commit()
        except:
            self.conn.rollback()
            return Exception
        return res


if __name__ == '__main__':
    s = Sqlite3Util("sqlite3.db")
    # sql = "CREATE TABLE user (username varchar(255) primary key, age int ,sex int default 0, mobile varchar(255), email varchar(255), nickname varchar(255), address text, sub_info text,detail text,create_time datetime DEFAULT (datetime('now','localtime')), update_time default (datetime('now','localtime')));"
    sql = "CREATE TABLE app (username varchar(255)  not null primary key, app_id varchar(255), secret varchar(255), detail text, create_time datetime default (datetime('now','localtime')));"
    s.insert(sql)
    # s.insert("insert into user (username, age, sex) values ('user1', 10, 1)")
    # print(s.select("select * from user"))
    # print(s.delete("drop table app"))


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值