sqlite 数据库Python文件

xu3bshqb  于 2023-01-31  发布在  SQLite
关注(0)|答案(2)|浏览(137)

如何在python中创建数据库文件?
我不太清楚如何使用SQLite将Python链接到数据库,因为updateDB函数不起作用。这段代码应该起作用,但更新没有正确工作。
我错过了什么?

import sqlite3

class Database:
    def __init__(self):
        self.DBName ='BUYHIRELtd.db'

    def connect(self):
        conn = None
        try: 
            conn = sqlite3.connect(self.DBName)
        except Exception as e:
            print(e)
        return conn

    def queryDB(self, command, params=[]):
        conn = self.connect()
        cur = conn.cursor()
        cur.execute(command, params)
        result = cur.fetchall()
        self.disconnect(conn)
        return result

    def updateDB(self, command, params=[]):
        conn = self.connect()
        cur = conn.cursor()
        cur.execute(command, params)
        result = cur.fetchall()
        self.disconnect(conn)
        return result

    def disconnect(self, conn):
        conn.close()
kqqjbcuj

kqqjbcuj1#

缺少conn.commit,无法保存对数据库的更改。

import sqlite3

class Connector:
    dbName = "Database.db"

    def connect(self):
        conn = None
        try:
            conn = sqlite3.connect(self.dbName)
        except Exception as e:
            print(e)
        return conn

    def disconnect(self, conn):
        conn.close()

    def queryDB(self, command, params=[]):
        conn = self.connect()
        cur = conn.cursor()

        cur.execute(command, params)
        result = cur.fetchall()

        self.disconnect(conn)
        return result

    def updateDB(self, command, params=[]):
        conn = self.connect()
        cur = conn.cursor()

        cur.execute(command, params)
        conn.commit()
        result = cur.fetchall()

        self.disconnect(conn)
        return result
vq8itlhq

vq8itlhq2#

请确保您正在www.example.com文件的顶部导入sqlite3database.py,否则命令将无法运行。

相关问题