Reputation: 950
So I am making a tag bot in discord.py with SQLite but I have a problem. This is the code so far:
sql.execute(f'select tag_name from tags_list where tag_name ={name}')
does_exist = sql.fetchone()
if does_exist is None:
sql.execute('insert into tags_list(tags_name, tags_content) values(?,?)', (name, content))
db.commit()
await ctx.send(f":white_check_mark: Created tag with the name `{name}`")
else:
await ctx.send(f"Tag named `{name}` already exists!")
The problem is that does_exist
is meant to check if the tag already exists or not, but it doesn't. It doesn't do anything else either. This is how the table looks right now:
The code works without the if else statement. I can't figure the problem out, can someone help?
Upvotes: 3
Views: 4145
Reputation: 436
So it looks like you've referred to the tag_name
column by as tags_name
sql.execute(f'select tag_name from tags_list where tag_name ={name}')
# ^^^^^^^^ ^^^^^^^^
does_exist = sql.fetchone()
if does_exist is None:
sql.execute('insert into tags_list(tags_name, tags_content) values(?,?)', (name, content))
# ^^^^^^^^^
db.commit()
await ctx.send(f":white_check_mark: Created tag with the name `{name}`")
else:
await ctx.send(f"Tag named `{name}` already exists!")
Please tell me if this works
EDIT:
So I created a test version based on your code and it works fine:
import sqlite3
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS tag_list (
tag_name string NOT NULL,
tag_content
)""")
for i in range(0, 2):
name = 'donut'
content = 'choclate cream'
print("Name:", name, "Content:", content)
c.execute('select tag_name from tag_list where tag_name = ?', (name,))
does_exist = c.fetchone()
print("Exists?", does_exist)
if does_exist is None:
c.execute('insert into tag_list(tag_name, tag_content) values(?, ?)', (name, content))
conn.commit()
print('Created', name)
else:
print(name, 'already exists')
Output:
Name: donut Content: choclate cream
Exists? None
Created donut
Name: donut Content: choclate cream
Exists? ('donut',)
donut already exists
I think the problem may be in this line:
sql.execute(f'select tag_name from tags_list where tag_name ={name}')
# Change it to
sql.execute('select tag_name from tags_list where tag_name =t', (name,))
That should work
Upvotes: 2