简体   繁体   English

如何使用python和sqlite3创建新数据库

[英]How to create a new database using python and sqlite3

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?如果我连接到数据库文件时它不存在,有没有办法自动创建它?

如果不存在,您提供的代码确实会创建'D:\\\\aaa.db'

如果它不是自动创建的,请确保您拥有正确的目录权限

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.第一个将始终有效,因为您在已经存在的目录中工作,如果您不事先创建 te 文件夹,则第二个将不起作用。

如果文件不存在,很确定 .connect 将创建该文件。

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

.connect 应该即时创建一个新的数据库文件,因为子目录确实存在,并且您有足够的权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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