0

The script from the command line, should it save example.db file in the same directory?

Where is the example.db file?

import  sqlite3
conn = sqlite3.connect('example.db')

c = conn.cursor()

c.execute('''CREATE TABLE IF NOT EXISTS food_db
                (item, calories, total fat, protein)''')

conn.commit()

food_items = [  ('Broccoli Chinese',    22,     0.7,    1.1),
                ('chia seeds',          490,    30.8,   15.6),
                ('blueberries',         57,     0.3,    0.7),]

c.executemany('INSERT INTO food_db VALUES (?,?,?,?)',food_items)

for row in c.execute('SELECT * FROM food_db ORDER BY calories'):
    print(row)

conn.close()

This script is in the same directory

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()

for row in c.execute('SELECT * FROM food_db ORDER BY calories'):
    print(row)

Run on the command line, nothing gets returned, no error, just nothing. Why does it not return the rows that the database should contain?

Edit: ok looks like i just needed a

conn.commit()

after i inserted into the table to save it then it returns also with the second script.

but my first questions still remains, where is the example.db file?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Runner Bean
  • 4,895
  • 12
  • 40
  • 60

1 Answers1

2

The form of the connect function you've used saves the database in a file (called example.db) in your current directory.

This means that if you're calling the script from another directory, a new database will be created. If possible, I would use an absolute path.

Kendas
  • 1,963
  • 13
  • 20
  • im calling the script from the command line like this C:\Users\me\Anaconda2\python.exe c:\users\me\diet\sqlite_tutorial.py so im calling it from the same directory that it saved in? but the example.db is not saved in this directory? – Runner Bean Aug 30 '19 at 02:54
  • No, you're running it from the directory you're in while entering the command – Kendas Aug 30 '19 at 03:01
  • If you want to find out which directory you're in on the command line, look at this answer: https://stackoverflow.com/questions/921741/windows-equivalent-to-unix-pwd – Kendas Aug 30 '19 at 03:05