python下向sqlite插入记录,是否存在过记录的判断不起作用
怪我咯
怪我咯 2017-04-18 09:04:44
0
1
596

每次都是返回 False

import sqlite3

conn = sqlite3.connect('urls.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS  urls (id integer primary key autoincrement, link text)') 

def url_exists(url):
    sql_cmd = '''select * from urls where link = '%s' ''' % url
    cursor.execute(sql_cmd)
    res = cursor.fetchall()
    if len(res) > 0 :
        print '%s exists' % url
        return True
    else:
        sql_cmd_2 = '''insert into urls(link) values('%s') ''' % url
        cursor.execute(sql_cmd_2)
        print '%s added' % url
        return False
    cursor.close()
    conn.commit()
    conn.close()

url_status = url_exists('example.com')
print url_status
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
小葫芦

Because you returned True directly after adding it, and the database was not committed. . .

import sqlite3

conn = sqlite3.connect('/tmp/urls.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS  urls (id integer primary key autoincrement, link text)') 

def url_exists(url):
    sql_cmd = '''select * from urls where link = '%s' ''' % url
    cursor.execute(sql_cmd)
    res = cursor.fetchall()
    suc = True
    if len(res) > 0 :
        print '%s exists' % url
        suc = True
    else:
        sql_cmd_2 = '''insert into urls(link) values('%s') ''' % url
        cursor.execute(sql_cmd_2)
        print '%s added' % url
        suc = False
    cursor.close()
    conn.commit()
    conn.close()
    return suc

url_status = url_exists('example.com')
print url_status
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!