How to create a new database using python and sqlite3

PythonSqlite

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

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

Solution 6 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionzjm1126View Question on Stackoverflow
Solution 1 - PythonAlex MartelliView Answer on Stackoverflow
Solution 2 - PythonJohn La RooyView Answer on Stackoverflow
Solution 3 - PythonGaketView Answer on Stackoverflow
Solution 4 - PythonDonald ByrdView Answer on Stackoverflow
Solution 5 - PythonalexView Answer on Stackoverflow
Solution 6 - Pythonuser169309View Answer on Stackoverflow