如何使用SQL参数

How to use SQL parameters

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

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

# 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]

而不是 WHERE username = 'John Smith',我想要一个将 name 参数传递到此命令的解决方案,因此无论 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']。

VALUES 是 INSERT statement 的必需部分。

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

    command = ("""
                SELECT score FROM players
                WHERE username = ?
                """)
    params = ['John Smith']
    return cur.execute(command, params).fetchone()[0]
example_data = [("John Smith", "Password", 10)]
cur.executemany("""
                INSERT INTO players
                VALUES (?, ?, ?)""",

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