0

I have a table (server_ preference) which has these headers: guild_id - int mod_channel_role_id - int report_channel_id - int i want to check if guild_id exist in the guild id column if it does not i want to insert to the table new staff i have tried many things and haven’t found any thing that worked this was my last attempt

conn = sqlite3.connect("server_preference.db")
    c = conn.cursor()
    for guild in client.guilds:
        c.execute("""IF NOT EXISTS ( SELECT guild_id FROM server_preference WHERE guild_id = ?)
                     BEGIN
                     INSERT INTO server_preference (guild_id) VALUES (:guild_id)
                     END""", guild.id)
        conn.commit()
    conn.close()

and I got this error:

sqlite3.OperationalError: near "IF": syntax error

1
  • SQLite flavor sql syntax is documented at sqlite.org/lang.html ... Nowhere will you find a command starting with IF. You can't just throw random stuff at it and hope it works. Commented Apr 25, 2020 at 11:10

2 Answers 2

1

If you don't want duplicate guild_ids in your table, then you should have the database enforce uniqueness with a unique constraint or index (they are pretty much equivalent).

So, start with:

CREATE UNIQUE INDEX unq_server_preference_guild_id ON server_preference(guild_id);

Then, if you run:

INSERT INTO server_preference (guild_id) VALUES (:guild_id);

You will get an error. If you want to avoid an error, use an ON CONFLICT clause:

INSERT INTO server_preference (guild_id)
    VALUES (:guild_id)
    ON CONFLICT (guild_id) DO NOTHING;
Sign up to request clarification or add additional context in comments.

Comments

0

You can implement this logic in a sngle statement by using the insert ... select syntax with a not exists condition:

insert into server_preference(guild_id)
select :guild_id
where not exists (select 1 from server_preference where guild_id = :guild_id)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.