[Tutor] sqlite3 making a spurious duplicate?

Alan Gauld alan.gauld at yahoo.co.uk
Mon Apr 17 20:19:11 EDT 2017


On 18/04/17 00:36, Marilyn Davis wrote:
> #!/usr/bin/env python3
> """
> Hello Tutors,
> 
> I can't figure out why the FillWithStars() function puts Canopus in the db
> twice.
> 
> What am I missing?

I don;t know but I converted your script into the more
conventional form and it worked. it was the fetchall()
line that made the difference... I don't understand
why your code seems to behave oddly, but its too late
to figure out right now, hopefully someone else can
answer... Here is my version:

import os, sqlite3, subprocess

def FillWithStars():

    with sqlite3.connect("stars.db") as connection:

        cursor = connection.cursor()
        cursor.execute("DROP TABLE IF EXISTS brightest")

        cursor.execute("""
            CREATE TABLE brightest(
            name,
            constellation,
            apparent_magnitude,
            absolute_magnitude,
            distance)""")
        cursor.execute("""INSERT INTO brightest
                          VALUES("Canopus", "Carina", -0.72, -2.5, 74)""")

        stored_stars = cursor.execute("SELECT * FROM BRIGHTEST")

        for star in stored_stars:
            print('---> ', star)

        cursor.execute("INSERT INTO brightest VALUES(?, ?, ?, ?, ?)",
                           ("Arcturus", "Bootes", -0.04, 0.2, 34))

        stored_stars = cursor.execute("SELECT * FROM BRIGHTEST")

        for star in stored_stars.fetchall():
            print(star)

def main():
    FillWithStars()

if __name__ == '__main__':
    main()


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list