简体   繁体   English

(Python3) 检查变量是否在 sqlite3 数据库中

[英](Python3) Check if a variable is in an sqlite3 Database

im programming a Discord bot.我正在编写一个 Discord 机器人。 It saves Usernames and theire money in a sqlite3 database.它在 sqlite3 数据库中节省了用户名和他们的钱。 Now i need to check if a Username is alredy in the Database to prevent double entries.现在我需要检查数据库中是否有用户名以防止重复输入。

money4 = 1000


def add_player(user):
    cursor.execute("INSERT INTO player VALUES (?,?)", (str(user), int(money4)))
    connection.commit()

thats the code to add the name into the database.这就是将名称添加到数据库中的代码。 With that people can get double entries and i just want to block that.有了这个,人们可以获得双重条目,我只想阻止它。 edit: Database looks like this with multiple entries:编辑:数据库看起来像这样有多个条目:

[('message.author', 1000), ('Micheltv10#9087', 1000), ('bempel#2040', 1000), ('bempel#2040', 1000), ('Micheltv10#9087', 1000), ('Micheltv10#9087', 1000), ('Micheltv10#9087', 1000), ('Micheltv10#9087', 1000), ('Micheltv10#9087', 1000)]

You could try to select the username before inserting to check if it already exists.您可以尝试在插入之前选择用户名以检查它是否已经存在。 Or do it properly and make the username unique (maybe as the primary key) in your database structure, so inserting duplicates would throw an error.或者正确执行并在您的数据库结构中使用户名唯一(可能作为主键),因此插入重复项会引发错误。

I solved it by creating a table with a primary key.我通过创建一个带有主键的表来解决它。

cursor.execute("""CREATE TABLE spieler(
            spielername TEXT PRIMARY KEY,
            money INTEGER
            )""")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM