python - 如何使用 SQL 参数

标签 python sqlite sqlparameter

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

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

# 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',因此无论名称参数是什么,都会成为正在搜索的术语。

我在这里找到了一个类似的示例(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]

关于python - 如何使用 SQL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35149299/

相关文章:

python - 正则表达式:在前瞻断言的最后一场比赛之后直到前瞻断言的第一场比赛之后查找文本

Python Pylab,如何更改指定 Axis 大小的标签的大小

python - 在运行时在 Django 中指定关系动词?

java - 使用相同的查询插入多个值 SQLite android

.net - System.Data.SqlClient.SqlParameter.IsNullable 的用途是什么?

c# - 将 SqlParameter 添加到 SqlParameterCollection 时出现 NullReferenceException

python - 创建每个键有多个值的字典

android - SharedPreferences 或 SQlite

java - 如何从 getMetaData.getColumns() 返回可滚动的结果集?

mysql - 在 MySQL 查询中重新定义/重新设置参数