[py004] sqlite3上手急用

Friday, June 5, 2020 ---Andy

一、導(dǎo)入sqlite3模塊+定義sql執(zhí)行函數(shù)

import sqlite3

class MySqlite:
    def __init__(self,database="Andy.db"):
        self.database = database
        
    def execute(self,sql=''):
        """執(zhí)行sql語(yǔ)句,@return: select操作:rows-->[()...]"""
        try:
            # 1.連接數(shù)據(jù)庫(kù)
            conn = sqlite3.connect(self.database)
            # 2.執(zhí)行sql:以查詢數(shù)據(jù)庫(kù)里面包含的所有表為例
            rows = [row for row in conn.execute(sql)]
            # 插入-刪除-修改:需要提交
            conn.commit()
            # 3.關(guān)閉數(shù)據(jù)庫(kù)
            conn.close()
            return rows
        except Exception as e:
            print(e)
            
    def tables(self):
        """查看所有表"""
        return self.execute(sql='select name from sqlite_master')
        
    def table_info(self,table='sqlite_master'):
        """查看表的結(jié)構(gòu)"""
        return self.execute(sql=f"PRAGMA table_info({table})")
        
    def show(self,table='sqlite_master'):
        """查看表的數(shù)據(jù)"""
        return self.execute(sql=f"select * from {table}")

二、創(chuàng)建表,查詢存在的表,查看表結(jié)構(gòu)

# 2-1.自動(dòng)創(chuàng)建sqlite3_test_db.db數(shù)據(jù)庫(kù)文件,并創(chuàng)建表
sqli = MySqlite('sqlite3_test_db.db')
sqli.execute("create table user(name text PRIMARY KEY NOT NULL, age int)")
# 2-2.查詢當(dāng)前數(shù)據(jù)庫(kù)有哪些表
sqli.tables()
[('user',), ('sqlite_autoindex_user_1',)]
# 2-3.查詢表結(jié)構(gòu)
sqli.table_info(user)
[(0, 'name', 'text', 1, None, 1), (1, 'age', 'int', 0, None, 0)]

三、數(shù)據(jù)增刪改查

# 3-1 增
sqli.execute("insert into user values('Andy',18)")
sqli.execute("insert into user values('Amanda',18)")
# 3-2 刪
sqli.execute("delete from user where name = 'Amanda'")
# 3-3 改
sqli.execute("update user set age=19 where name = 'Andy'")
# 3-4 查
sqli.execute("select * from user")
[('Andy', 19)]

【完】

[1].過(guò)程中有任何問(wèn)題,歡迎交流!Q597966823

??讓知識(shí)或技術(shù)實(shí)現(xiàn)其最大的價(jià)值,歡迎收藏自用、轉(zhuǎn)載分享,轉(zhuǎn)載請(qǐng)注明原文出處,謝謝!
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容