[Tutor] sqlite3 making a spurious duplicate?

Marilyn Davis marilyn at pythontrainer.com
Mon Apr 17 19:36:50 EDT 2017


#!/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?

Thank you for any help.

Marilyn Davis

p.s. That Reset(db_name) is in there so that you can run it over and over
if you want.

---
"""
import os, sqlite3, subprocess

def Reset(db_name):
    os.system("rm " + db_name)
    db_process = subprocess.Popen(("sqlite3", db_name),
                                   stdin=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
    for send in (b'.tables', ):
        returned = db_process.communicate(send)
        assert returned == (b'', b'')

def FillWithStars():

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

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

        connection.executemany("INSERT INTO brightest VALUES(?, ?, ?, ?, ?)",
            [("Arcturus", "Bootes", -0.04, 0.2, 34),])

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

    for star in stored_stars:
        print(star)

def main():
    Reset("stars.db")
    FillWithStars()

if __name__ == '__main__':
    main()

"""Output:

bash-3.2$ ./why3.py
('Canopus', 'Carina', -0.72, -2.5, 74)
('Canopus', 'Carina', -0.72, -2.5, 74)
('Arcturus', 'Bootes', -0.04, 0.2, 34)
bash-3.2$
"""



More information about the Tutor mailing list