0

在问这个看似简单的问题之前,我已经进行了广泛的搜索。我有一个 python 项目,制作了一个 sqlite DB 和一些代码来插入和使用它,一切都很好,直到我决定将 db 函数从主文件中拉出,然后拉出 db 文件,并将两者都放入名为 db 的文件夹。所以现在函数文件和数据库都在同一个文件夹中,一层深。所以错误立即开始,但代码仍然运行,虽然实际上没有做任何事情,我搜索互联网,我看到的只是人们说要删除数据库文件,重新制作它,这通常可以解决问题,我做到了两次但没有运气。我在这里想念什么?代码运行没有错误,但实际上并没有工作,我在这里报告的错误来自 pycharm 悬停框。


def add_symbols_to_list(symbols_to_add) -> None:
    """This will add symbols to the current symbols list, but leave the previous entries.
    :param: a list of user provided symbols as comma separated strings."""
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    time_now = datetime.datetime.now()  # get current time for the int conversion below
    this_month_int = time_now.month  # get the current month and set it to an int

    # gets the current number of rows so new additions have the correct rowid
    # c.execute("SELECT * FROM currentMonthStocks")
    # current_row_number = c.execute("SELECT COUNT(*) FROM currentMonthStocks")
    # rows = int(current_row_number)
    # # https://www.sqlitetutorial.net/sqlite-count-function/
    # db_row_id = rows + 1  # set the first row number

    extra_symbols = symbols_to_add

    for i in range(len(extra_symbols)):
        c.execute("""INSERT INTO currentMonthStocks
                   (symbol, month)
                   VALUES (?, ?)""", (extra_symbols[i], this_month_int))
        # db_row_id += 1
        print("Added a symbol")
    print("Symbols successfully populated into currentMonthStocks table in database.db")


new_symbols = ['tsla', 'dis', 'pltr']
add_symbols_to_list(new_symbols)


def get_symbols_at_month_start() -> None:
    """Function inserts a list of symbols to trade every month into the currentMonthStocks table in database.db.
    This is called once at the start of the month, deletes the current symbols and adds the new ones.
    :return: None."""

# edited out the url info for brevity    
response = requests.request("POST", url, headers=headers, data=payload)
    symbols = response.json()['content']['allInstrumentRows']
    this_months_symbols = []

    for symbol in symbols:
        this_months_symbols.append(symbol['Symbol'])
    # print(this_months_symbols)

    # file = "database.db"
    try:
        conn = sqlite3.connect('database.db')  # setup database connection
        c = conn.cursor()
        print("Database Connected")

        # c.execute("""CREATE TABLE currentMonthStocks (
        #             id INT PRIMARY KEY,
        #             symbol TEXT,
        #             month INT)""")
        # print("table created successfully")

        # # checks to see if there is at least 1 row in the db, if yes it deletes all rows.
        if c.execute("SELECT EXISTS(SELECT 1 FROM currentMonthStocks WHERE id=1 LIMIT 2);"):
            # for i in range(len(this_months_symbols)):
            c.execute("DELETE FROM currentMonthStocks")
            print("Delete all rows successful")

        time_now = datetime.datetime.now()  # get current time for the int conversion below
        this_month_int = time_now.month  # get the current month and set it to an int
        db_row_id = 1  # set the first row number

        for i in range(len(this_months_symbols)):
            c.execute("""INSERT INTO currentMonthStocks
                       (id, symbol, month)
                       VALUES (?, ?, ?)""", (db_row_id, this_months_symbols[i], this_month_int))
            db_row_id += 1
            # print("one more entry")
        print("Symbols successfully populated into currentMonthStocks table in database.db")

        conn.commit()  # commits the current transaction.
        print("Entries committed to database.db")
        # c.close()  # closes the connection to the db.
        conn.close()
    except sqlite3.Error as e:
        print("sqlite3 error", e)

    finally:
        if conn:
            conn.close()
            print("Database.db Closed")

4

1 回答 1

0

没有问题,或者至少没有解决方案,pycharm 仍然无法识别表格,但我写了 5 个 CRUD 函数,它们都可以工作。所以答案是不用担心,看看数据库是否正确更新。

于 2021-08-27T14:17:59.680 回答