在Windows中使用Django Sqlite
我想在Django开发中使用sqlite,设置如下:
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'D:\database.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
但是当我尝试执行syncdb时,出现了以下错误:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
438, in execute_manager
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 191,
in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 220,
in execute
output = self.handle(*args, **options)
File "C:\Python27\lib\site-packages\django\core\management\base.py", line 351,
in handle
return self.handle_noargs(**options)
File "C:\Python27\lib\site-packages\django\core\management\commands\syncdb.py"
, line 56, in handle_noargs
cursor = connection.cursor()
File "C:\Python27\lib\site-packages\django\db\backends\__init__.py", line 250,
in cursor
cursor = self.make_debug_cursor(self._cursor())
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line
207, in _cursor
self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file
有人知道这是怎么回事吗?我注意到我尝试过多次更改数据库的名称(位置),但都没有成功……
3 个回答
0
试着只用数据库文件的名字,不要加路径。默认情况下,Django会把它放在和manage.py文件同一个文件夹里。
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'database.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
1
这个对我有效
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'c:/projects/blog/first.db',
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Not used with sqlite3.
'PORT': '', # Not used with sqlite3.
}
}
1
首先,建议使用正斜杠或者 r''
字符串 来开始。
'default': {
# [... snip ...]
'NAME': 'D:/database.db',
# (or...) 'NAME': r'D:\database.db',
# [... snip ...]
}
另外,你还需要确保你的 Sqlite 文件所在的 整个目录 是可以写入的(在这个例子中是 D:/
),因为 Sqlite 需要在数据库文件旁边写一个日志文件。