71
import sqlite3

conn = sqlite3.connect(r"D:\aaa.db")

Is there a way to automatically create the db file if it doesn't already exist when I connect to it?

2
  • Are you asking how SQLite3 works when it creates a new, empty database? Commented Feb 3, 2010 at 3:08
  • so you want to check if the db is there if not create it? Commented Feb 3, 2010 at 3:09

6 Answers 6

96

The code you give does create 'D:\\aaa.db' if it doesn't exist.

Sign up to request clarification or add additional context in comments.

Comments

9

If it isn't created automatically, make sure that you have the directory permissions correct

Comments

6

As it was already mentioned, your code should work if you have permissions to write for this path. However, it is important that directory must exist. If you make call for non-existing folder:

conn = sqlite3.connect(r"D:\Some new non-existing folder\aaa.db")

It will not work, you will have

sqlite3.OperationalError: unable to open database file. 

The same is for relative paths:

1) conn = sqlite3.connect(r"aaa.db") 
2) conn = sqlite3.connect(r"Some new folder\aaa.db")

First will always work, because you are working in already existing directory and second will not work if you do not create te folder beforehand.

Comments

4

Pretty sure .connect will create the file if it doesn't exist.

Comments

2
import sqlite3
conn=sqlite3.connect('xx.db')
print "Database created and opened succesfully"

Comments

0

.connect should create a new database file on the fly, given sub-directories do exist, and you have adequate permissioning.

1 Comment

While the answer is correct imho it doesn't add any value: It's all been said before

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.