【问题标题】:How to use SQL parameters如何使用 SQL 参数
【发布时间】:2016-02-02 09:19:35
【问题描述】:

我正在尝试为我正在制作的一个简单游戏创建一个数据库,但在查询它以获取玩家统计信息时遇到了问题。至此数据库可以搜索更新,但只有修改实际代码才能改变搜索词。

到目前为止的整个代码(对任何缩进错误表示歉意):

# Importing modules
import sqlite3

# Creating database
base_db = sqlite3.connect("D:\\FILEPATH\\base_db")

# Creating  cursor object
global cur
cur = base_db.cursor()

# Creating players table with username etc. attributes
cur.execute("""
            CREATE TABLE IF NOT EXISTS players
            (username, password, score)
            """)
base_db.commit()


# Inserts some example data
def populate_db():
    print("Populating database")
    example_data = [("John Smith", "Password", 10)]
    cur.executemany("""
                    INSERT INTO players
                    VALUES (?, ?, ?)""",
                    example_data)
    base_db.commit()


# Clears database
def clear_db():
    print("Clearing database")
    command = ("""
                DELETE FROM players
               """)
    cur.execute(command)
    base_db.commit()


# Function that (only) updates the database
def update_db(mode, name):
    if mode is "score":
        print("Updating scores")
        print("Finding", name)
        command = ("""
                    UPDATE players
                    SET score = '0'
                    WHERE username = 'John Smith'
                    """)
        cur.execute(command)
    base_db.commit()


# Function that (only) retrieves data from the database
def retrieve_db(mode, name):
    # Returns value of player's score
    if mode is "score":
        print("Retrieving scores")
        print("Finding", name)
        command = ("""
                    SELECT score FROM players
                    WHERE username = 'John Smith'
                    """)
        return cur.execute(command).fetchone()[0]

# Returns tuple of username and password
elif mode is "login":
    print("Retrieving login details")
    print("Finding", name)
    command = ("""
                SELECT username, password FROM players
                WHERE username = 'John Smith'
               """)
    return cur.execute(command).fetchone()[0:2]
base_db.commit()

# Testing results
populate_db()

print(retrieve_db("score", "John Smith"))  # Expected result is 10
print(retrieve_db("login", "John Smith"))  # Expected result is ('John Smith, 'Password')

clear_db()

我正在尝试解决的部分:

# Function that (only) retrieves data from the database
def retrieve_db(mode, name):
    # Returns value of player's score
    if mode is "score":
        print("Retrieving scores")
        print("Finding", name)
        command = ("""
                    SELECT score FROM players
                    WHERE username = 'John Smith'
                    """)
        return cur.execute(command).fetchone()[0]

我想要一个将 name 参数传递给此命令的解决方案,而不是 WHERE username = 'John Smith',因此无论 name 参数是什么都会成为正在搜索的术语。

我在这里 (Searching SQLite Database with Python Variables) 找到了一个类似的示例,但我不知道如何在这段代码中实现 (?)、(变量) 的想法。

到目前为止我已经尝试过:

    command = ("""
                SELECT score FROM players
                WHERE username = VALUES (?)""", name)

    command = ("""
                SELECT score FROM players
                WHERE username VALUES (?)""", name)

非常感谢您提供的任何帮助。提前致谢。

为了将来参考,我得到的最终工作版本是:

    command = ("""
                SELECT score FROM players
                WHERE username = ?
                """)
    return cur.execute(command, name).fetchone()[0]

当函数被调用时,名称被提供为 ['John Smith']。

【问题讨论】:

  • 您已经在使用populate_db 中的参数。有什么问题?
  • 在该函数中,它只是将值插入到所有字段中,而不进行搜索。我的问题是在执行搜索的命令中实现使用 (?)、(variable) 的相同想法。到目前为止,我已经尝试了一些不同的变体,但都没有运气。
  • 编辑问题以显示您尝试过的内容。

标签: python sqlite sqlparameter


【解决方案1】:

VALUES 是INSERT statement 的必需部分。

参数标记 (?) 只是替换值本身:

    command = ("""
                SELECT score FROM players
                WHERE username = ?
                """)
    params = ['John Smith']
    return cur.execute(command, params).fetchone()[0]

【讨论】:

  • 还有一个问题,有没有办法对其进行重组,使参数不必是列表?
  • 没有。 'John Smith' 将被解释为包含十个字符的列表。
【解决方案2】:
example_data = [("John Smith", "Password", 10)]
cur.executemany("""
                INSERT INTO players
                VALUES (?, ?, ?)""",

你考虑过放弃吗?逗号太少

【讨论】:

    猜你喜欢
    • 2011-03-25
    • 2021-06-15
    • 2010-11-05
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多