使用 Flask/Sqlite 更新数据库表

时间:2021-05-16 14:07:05

标签: python sqlite flask

我正在尝试使其正常工作,并且在 pushNumber 中出现错误消息“第 49 行” cursor.execute(query_string,latestNumber) sqlite3.OperationalError: row value misused' 不断出现。除此之外,当使用 pop 函数时会出现:'sqlite3.OperationalError: table Stack has 1 columns but 3 values were provided'

我正在尝试获取它,以便当我访问 /calc/push/50 网页时,它会将 50 添加到列表中,然后在 Stack 数据库中创建一个表。当我输入 /calc/push/8 时,它会将 8 附加到列表中并将其插入到数据库中。一列应该只显示完整列表,每次通过推送更新,另一列应该显示我使用过的任何函数的所有日志,每次都在最后插入一条新记录。

from flask import Flask, render_template
import sqlite3

from flask.wrappers import Request

app = Flask(__name__)
conn = sqlite3.connect('stack.db')
cursor = conn.cursor()

stackList = []
latestNumber = 0    #For pop/peek function
columnCreated = 0

#cursor.execute("""CREATE TABLE Stack (
#                 StackLogs text
#                 Stacklist text
#              )""")
#conn.commit()

@app.route('/')
@app.route('/calc/')
@app.route('/calc/peek')
def calcPeek():
    return render_template('peek.html', latestNumber=latestNumber) #Prints top of stack - recent number. Could also use [-1]

@app.route('/calc/push/<number>') #<> passes number as a variable
def pushNumber(number):
    stackList.append(number)
    global latestNumber
    latestNumber = number #Assigns most recent number to this variable
    print(stackList)    #Prints to console so we can check the list
    global columnCreated
    columnCreated += 1
    print(columnCreated)

    if columnCreated == 1:
         conn = sqlite3.connect('stack.db')
         cursor = conn.cursor()
         stack_string = ', '.join('?' * len(stackList))
         query_string = 'INSERT INTO Stack VALUES (%s);' % stack_string
         cursor.execute(query_string, stackList)
         conn.commit()
         conn.close()
    elif columnCreated >= 2:
         conn = sqlite3.connect('stack.db')
         cursor = conn.cursor()
         stack_string = ', '.join('?' * len(latestNumber))
         query_string = 'UPDATE Stack SET StackLogs=(%s);' % stack_string
         cursor.execute(query_string, latestNumber)
         conn.commit()
         conn.close()

    return render_template('push.html', number=number, latestNumber=latestNumber)

@app.route('/calc/pop')
def calcPop():
    global latestNumber
    if stackList == []: #If empty, prints to console. Otherwise pops end off of list.
        print("Stack is empty")
    else: 
        stackList.pop()     #Removes last value by default

    conn = sqlite3.connect('stack.db')
    cursor = conn.cursor()
    stack_string = ', '.join('?' * len(stackList))
    query_string = 'INSERT INTO Stack VALUES (%s);' % stack_string
    cursor.execute(query_string, stackList)
    conn.commit()
    conn.close()

    return render_template('pop.html', stackList=stackList, latestNumber=latestNumber)

1 个答案:

答案 0 :(得分:1)

尝试删除您查询的括号:

UPDATE Stack SET StackLogs=%s;
INSERT INTO Stack VALUES %s;