Is this the way to go with SQLite

Cecil Westerhof Cecil at decebal.nl
Sun Aug 23 09:18:53 EDT 2015


I understood that with sqlite3 in Python you can not use prepared
statements. Below the way I solved this.

Also an URL is unique, so I need to check that if it is found, the
values are the same as the ones I wanted to insert.

This is my code.
========================================================================
select_url  = '''SELECT year
                 ,      month
                 ,      description
                 FROM   LINKS
                 WHERE  URL = ?'''
year        = 2015
month       = 8
for link in links:
    description = link[0]
    url         = link[1]
    url_values  = c.execute(select_url, [url]).fetchall()
    if len(url_values) == 0:
        print('Adding {0}'.format(link))
        c.execute('''INSERT INTO links
                     (year, month, description, URL)
                     VALUES
                     (?, ?, ?, ?)
                  ''',
                  [year, month, description, url])
    else:
        to_insert   = (year, month, description)
        found       = url_values[0]
        if found != to_insert:
            print('For {0} found {1} instead of {2}'.format(url, found, to_insert))
========================================================================

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof



More information about the Python-list mailing list