我正在尝试从不属于该项目的外部脚本访问Django项目中拥有的sqlite3数据库。
但是,以下内容将返回一个空列表:
con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
即使我已经将一些模型保存到数据库中。 要检查表名,我在Django shell中使用以下命令:
>>> tables = connection.introspection.table_names()
>>> seen_models = connection.introspection.installed_models(tables)
>>> seen_models
{<class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.sessions.models.Session'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'explorer_api.models.Athlete'>, <class 'django.contrib.admin.models.LogEntry'>, <class 'django.contrib.auth.models.Group'>, <class 'explorer_api.models.Activity'>, <class 'django.contrib.auth.models.User'>}
>>> tables
['auth_group', 'auth_group_permissions', 'auth_permission', 'auth_user', 'auth_user_groups', 'auth_user_user_permissions', 'django_admin_log', 'django_content_type', 'django_migrations', 'django_session', 'explorer_api_activity', 'explorer_api_athlete']
我还没有在模型的Meta中明确指定表名,所以我猜这些表名是appname_modelname
(explorer_api_activity
和explorer_api_athlete
)。
但是为什么要清空列表?
答案 0 :(得分:0)
从对问题的评论中: 是的,只要您具有文件的有效路径,就可以运行此脚本。我用以下较小的更改重写了您的脚本:
import sqlite3
import os.path
try:
file_name = raw_input("Enter File Path? ")
except:
file_name = input("Enter File Path? ")
if os.path.isfile(file_name):
con = sqlite3.connect(file_name)
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
else:
print("File does not exist")
用法:
> python sqlite_tables.py
(prompt)> Enter File Path? random/file/path
(prompt)> File does not exist
> python sqlite_tables.py
(prompt)> Enter File Path? /valid/path/to/database.db
(prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]
> python sqlite_tables.py
(prompt)> Enter File Path? ../database.db # relative path
(prompt)> [(u'django_migrations',), (u'sqlite_sequence',)...]