How to create a new database using python and sqlite3

Question:

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?

Asked By: zjm1126

||

Answers:

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

Answered By: Alex Martelli

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

Answered By: Donald Byrd

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

Answered By: John La Rooy

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

Answered By: user169309
import sqlite3
conn=sqlite3.connect('xx.db')
print "Database created and opened succesfully"
Answered By: alex

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 folderaaa.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 folderaaa.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.

Answered By: Gaket
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.