简体   繁体   中英

In python, when using sqlite3 where are databases stored physically?

Sorry for the basic questions. I'm starting to work with Python. I'm using Windows 10, Python 3.5, Notepad++ as editor. Python is installed in z:\\python35 and scripts are in z:\\python\\sqlite , then my script is really simple:

import sqlite3
conn = sqlite3.connect('sample.db')
c = conn.cursor()
c.execute("CREATE TABLE example (name VARCHAR)")
conn.close()

When I run the script inside Notepad++ (run as administrator) I execute z:\\python35\\python.exe -i "$(FULL_CURRENT_PATH)" . Looks like the script runs correctly, since it does nothing the first time run, but the next time it says:

sqlite3.OperationalError: table example already exits

And that's okay because I wanted to create the database and the table. Thing is, where does this sample.db is stored? I don't find it in the python directory or my projects directory. Not even by searching in Windows.

How can I delete the whole database?

It will be in the current working directory. You can see what this is by

import os
print(os.getcwd())

Once you know the directory you can find and delete the sample.db file.

probably in the "current directory" that notepadd++ uses. try to add on top of script:

import os
print(u"current directory: %s" % os.getcwdu())

maybe you could specify an absolute path for the db do deal with that uncertainty

If you do not need the databases to persist on your file system, you can store them in memory using the special :memory: name:

import sqlite3
conn = sqlite3.connect(':memory:')

One solution could be to change your current working directory like this:

#import os module

import os, sqlite3

#change cwd to the given absolute path with a raw string.
absolute_path = r"z:\db\directory_for_db"
os.chdir(absolute_path)
# connect to database
conn = sqlite3.connect('sample.db')
c = conn.cursor()
c.execute("CREATE TABLE example (name VARCHAR)")
conn.close()

Which will result in your .db being saved wherever you define absolute_path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM