首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Python中SQLite3主键自增与简单使用

Python中SQLite3主键自增与简单使用

作者头像
小锋学长生活大爆炸
发布2022-05-09 16:00:56
发布2022-05-09 16:00:56
1.3K00
代码可运行
举报
运行总次数:0
代码可运行

SQLite3解释可以自行搜索,这里直接上代码了。

仅包含建表、查询、插入三个简单地功能,仅供参考~

主键自增的关键是:`id` INTEGER PRIMARY KEY,不要有更多的修饰了,如AUTO_INCREMENT,加上反而会不行

代码语言:javascript
代码运行次数:0
运行
复制
# coding:utf-8

import sqlite3
import time
import datetime

class DB:
    def __init__(self):
        self.Start()
        self.CreatTable()
        self.Close()
        # print(self.id)

    def Start(self, path='sql.db'):
        self.conn = sqlite3.connect(path)
        self.cursor = self.conn.cursor()

    def CreatTable(self):
        try:
            sql = '''
            CREATE TABLE IF NOT EXISTS `ocr`(
               `id` INTEGER PRIMARY KEY,
               `user` VARCHAR(100) NOT NULL,
               `score` INTEGER UNSIGNED NOT NULL,
               `update_date` TIMESTAMP
            );
            '''
            self.cursor.execute(sql)
            return 1
        except Exception as e:
            print('>> Creat Error:', e)
            return 0

    def Insert(self, user, score):
        try:
            sql = '''
            INSERT INTO ocr ( id, user, score, update_date )
            VALUES
            (NULL, ?, ?, ?);
           '''
            self.Start()
            self.cursor.execute(sql, (user, score, datetime.datetime.now()))
            self.conn.commit()
            self.Close()
            return 1
        except Exception as e:
            print('>> Insert Error:', e)
            return 0

    def Select(self, id):
        self.Start()
        self.cursor.execute('''SELECT * from ocr WHERE id=(?);''', (id,))
        res = self.cursor.fetchall()
        self.Close()
        return res

    def Close(self):
        self.cursor.close()
        self.conn.close()

    def SelectALL(self):
        self.Start()
        sql = "SELECT * from ocr;"
        self.cursor.execute(sql)
        res = self.cursor.fetchall()
        self.Close()
        return res


if __name__ == '__main__':
    db = DB()
    db.Insert('1', '4')
    res = db.SelectALL()
    print(res)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档