簡體   English   中英

測驗所需的 sqlite3 python 查詢不起作用

[英]sqlite3 python query needed for quiz isn't working

對於我的學校項目,我決定制作一個物理修訂工具。 該工具允許用戶登錄並保存有關他們在某些問題上的表現的信息。 因此,我意識到我需要命名用於存儲每個用戶分數的每個表,所以我認為使用 .format 是合適的。 在我需要添加將信息添加到表中的代碼之前,它似乎工作正常。 從到目前為止我對代碼所做的測試來看,我認為問題是因為我使用的是 .format 它實際上不會創建任何列。 我不知道如何解決這個問題,請幫忙。 提供了適當的代碼部分:

def quesprep():
intro.destroy()
con= sqlite3.connect("login.db")
c= con.cursor()
c.execute("SELECT accid FROM credentials WHERE accountname = ?", (user,))
global results
results=c.fetchall()
con.commit()
con.close()
con= sqlite3.connect("store.db")
c= con.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS {}(mod integer, ques integer,score integer)""".format(results))
c.execute("INSERT INTO {} Values(mod=2,ques=1, score=0)".format(results))
con.commit()
con.close()
ques()


def mod2q1page():
questionspage.destroy()
con= sqlite3.connect("login.db")
c= con.cursor()
c.execute("SELECT accid FROM credentials WHERE accountname = ?", (user,))
global results
results=c.fetchall()
con.commit()
con= sqlite3.connect("store.db")
c= con.cursor()
c.execute("INSERT OR IGNORE INTO {} VALUES(mod=2, ques=2, score=0)" .format(results))

這里似乎有幾件事不對。

格式在 {} 中使用一個變量......例如 {0}、{1} 等

占位符是格式化 sql 查詢的首選途徑……就像你在 SELECT 中所做的那樣

我不確定這里的問題是什么,但是如果您嘗試添加列,則需要更改表......而不是插入。 INSERT 將添加一個行項目。 如果您可以發布錯誤,也許我們可以提供更多幫助。 不過,首先,請嘗試使用占位符代替格式。

此外,fetchall 返回一個元組列表......需要在 sql 中發送一個元組,而不是一個列表。

for x in results:
    c.execute("INSERT INTO ? (col1, col2, col3) VALUES (1, 2, 3);", x)

編輯:

我的立場更正了 - 我運行了這個代碼:

    data = [('user',)]
    cursor.execute("INSERT INTO ? (id, email, password) VALUES (1, test, test);", data)

語法錯誤,因為您無法向表名添加占位符。 在這里閱讀

我將格式與 {0} 一起使用:

cursor.execute("INSERT INTO {0} (id, email, password) VALUES (1, test, test);".format('user'))

查詢成功。 我相信這是你的問題。

找到了解決辦法:

intro.destroy()
con= sqlite3.connect("login.db")
c= con.cursor()
c.execute("SELECT accountname FROM credentials WHERE accountname = ?", (user,))
results=c.fetchone()
global tablename
tablename=" ".join(map(str, (results)))
con.commit()
con.close()
global m
m="mod"
global q
q="ques"
global s
s="score"
fieldtype="INTEGER"
con=sqlite3.connect("store.db")
c=con.cursor()
c.execute('CREATE TABLE IF NOT EXISTS {} ({fc} {ft}, {sc} {ft2}, {tc} {ft3})'\
          .format(tablename, fc=m, ft=fieldtype, sc=q, ft2=fieldtype, tc=s, 
ft3=fieldtype))
    con.commit()
    con.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM