【问题标题】:Using an array of values to store into the database使用一组值存储到数据库中
【发布时间】:2021-02-13 10:40:54
【问题描述】:

我的目标:将分数数组存储到表格中。

为什么是数组?使用该数组是因为我使用 pygame 收集了分数,并将每次尝试获得的每个分数保存在数组中,直到达到 10 次尝试并将数组传递到此处。

我希望从游戏中存储的数组中获取这些分数并将其存储到数据库中。如您所见,列 score1 到 score10 和 = ?因为我不知道在问号里填什么。

我尝试使用 INSERT INTO 将其插入到数据库中,但我不能,因为我需要指定我需要它的 ID。我只能使用 UPDATE 来代替。

有没有办法可以使用这个分数数组将其存储到数据库中?

注意:我不能只将玩家获得的分数写入“?”因为分数会有所不同。 SELECT 只是用来查看它是否有效。

非常感谢。

import sqlite3

conn = sqlite3.connect(':memory:')

conn.cursor()

score = [100, 20, 1000, 1002, 129, 1039, 400, 30, 300, 30]

    
conn.execute("""UPDATE Defender
            SET score1=?, score2=?,
            score3=?, score4=?,
            score5=?, score6=?,
            score7=?, score8=?,
            score9=?, score10=?
            WHERE defender_id=1""")

conn.commit()

conn.execute("SELECT score1 FROM Defender WHERE defender_id=1")

print(conn.fetchall())

conn.close()

【问题讨论】:

    标签: python arrays python-3.x sqlite


    【解决方案1】:

    一般execute() 函数可以接受两个参数:查询本身和作为元组的数据(如果需要):

    conn.execute(query, data)
    

    所以你可以说:

    query = """UPDATE Defender
                SET score1=?, score2=?,
                score3=?, score4=?,
                score5=?, score6=?,
                score7=?, score8=?,
                score9=?, score10=?
                WHERE defender_id=1""" #your query
    
    score = [100, 20, 1000, 1002, 129, 1039, 400, 30, 300, 30] #your data
    
    conn.execute(query, tuple(score))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-27
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      相关资源
      最近更新 更多