如何在sqlite3表中插入数据,同时使用python检查是否存在

问题描述 投票:0回答:1

我正在尝试使用电报API存储电报聊天中的用户ID,因此我决定将其存储在数据库中,以检查网址是否已发送给用户这是我制作的2个表,一个表user保留idchatID,ID自动递增,另一个表URLS保留已发送图片的网址,并且还有一个ID指向。

curr.executescript('''
CREATE TABLE IF NOT EXISTS URLS ( 

   link VARCHAR UNIQUE

);
CREATE TABLE IF NOT EXISTS USERS ( 
    ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    chatID INT(10) UNIQUE,
    FOREIGN KEY (ID) REFERENCES URLS(link)

   )''')

代码:

def from_red():
count = 1
for subm in reddit.subreddit('Memes').hot(limit=limit):

    if subm.url.endswith('.png') or subm.url.endswith('.jpg'):
        urlId = subm.url[18:][:-4] 
        info = last_data('getUpdates')
        userid = get_chat_id(info)

        curr.execute('SELECT link from URLS WHERE link = ? ',(urlId, ))
        url1 = curr.fetchone()

        curr.execute('SELECT chatID FROM USERS WHERE chatID = ? ', (userid ,))
        user1 = curr.fetchone()

        print(userid, user1, url1)

        # curr.execute('SELECT USERS.ID , URLS.link FROM USERS JOIN URLS ON USERS.ID = URLS.id')
        # fin = curr.fetchone()
        if (url1 and user1) :
            send_msg('Dude stop, get a real life')
            print('exists')
        else:
            curr.execute('INSERT OR IGNORE INTO URLS (link) VALUES (?) ', ( urlId ,))
            curr.execute('INSERT OR IGNORE INTO USERS (ID , chatID) VALUES (? , ?) ', (count , userid ))
            connection.commit()
            send_pic(subm.url , subm.title)
            time.sleep(0.5)
        count += 1  
        connection.commit()

问题是,只有第一条记录插入数据库中,其他chatID和url被忽略,并且从send_pic(subm.url , subm.title)执行的代码这是发生了什么:对于第一个用户

675805716 None None
675805716 (675805716,) None
675805716 (675805716,) None
675805716 (675805716,) None

第一个用户再试一次

675805716 (675805716,) ('ksf1010q0t351',)
exists
675805716 (675805716,) ('eqco251d3t351',)
exists
675805716 (675805716,) ('8lzgza889t351',)
exists
675805716 (675805716,) ('zot2yezfls351',)
exists

[当第二个用户尝试时:前两个不存在,其余的存在,我在这里真的很困惑:(

675805716 None ('ksf1010q0t351',)
675805716 None ('wgendg2yjt351',)
1031910401 (1031910401,) ('m/o19dhKr',)
exists
1031910401 (1031910401,) ('czspg4pkgt351',)
exists


尚未插入第二个用户的ID

现在添加第二个用户第二次尝试的counter to increment the id之后,出现了有趣的部分:给出所有存在的内容!


675805716 (675805716,) ('eqco251d3t351',)
exists
675805716 (675805716,) ('8lzgza889t351',)
exists
675805716 (675805716,) ('czspg4pkgt351',)
exists
...
python sqlite reddit python-telegram-bot
1个回答
0
投票

问题是您不断插入具有相同主键的内容。所有用户均插入user-id = 1。行

curr.execute(
   'INSERT OR IGNORE INTO USERS (ID , chatID) VALUES (1 , ?) ', 
   (userid , ))

将对表的用户ID列使用值1,对聊天ID使用变量userid的值。下次您尝试在表中插入一个值时,它会注意到主键“ 1”已被使用,不会插入任何内容。

更新:

[仅插入第一个URL,根据您要打印的日志,您几乎总是进入if语句的第一分支-带有print('exists')的分支。这就是为什么您甚至都没有尝试向数据库添加新条目的原因。

© www.soinside.com 2019 - 2024. All rights reserved.