sqlite 为什么我得到“没有这样的表”当运行SQL查询与cursor.execute()?

5kgi1eie  于 2023-02-23  发布在  SQLite
关注(0)|答案(1)|浏览(217)

我正在尝试运行一个简单的SQL查询,但一直收到“操作错误:No Such Table customers”有关代码为:

cursor = connection.cursor()
cursor.execute("SELECT * FROM customers")
# cursor.fetchone() or cursor.fetchall()
r = cursor.fetchone()
print(r)

奇怪的是运行一个原始的SQL查询使用下面的代码的作品,我能够通过行迭代和显示在HTML:

sql = "SELECT * FROM customers"
customer = Customer.objects.raw(sql)[:10]
print(customer)
print(connection.queries)

当我在debug_toolbar中为上面的第二个代码解释SQL时,我得到了看起来正确的代码:

Executed SQL
SELECT *
  FROM customers
Time
1.1129379272460938 ms
Database
network_db

另外奇怪的是django文档说要添加应用程序名称,所以当添加app_name network到第二个代码时,我得到一个错误消息no such table: network_customers,但是如果我按照第二个代码删除应用程序名称,代码就可以工作了。

sql = "SELECT * FROM network_customers"
customer = Customer.objects.raw(sql)[:10]
print(customer)
print(connection.queries)

www.example.com中的数据库settings.py:

DATABASES = {
    'default':{ 
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    },
    'network_db':{
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'Network.sqlite3',
    },
    'simulation_db':{
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'Simulation.sqlite3',
    }
}

网络apps.py:从django.apps导入AppConfig

class NetworkConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'network'

所以我想知道为什么第二个代码工作,但第一个代码不工作?我已经检查了调试工具栏,其中显示BaseDir是我正在查询的数据库所在的位置,所以我不认为这是一个问题。

溶液

通过使用下面的代码指定表所在数据库的位置,我能够修复第二个代码。我仍然不明白为什么我的select语句在没有指定应用程序名称(如select * from appname_tablename")的情况下工作

database='C:/EXACTLOCATION/../../Network.sqlite3'
db=sqlite3.connect(database)
c=db.cursor()

sql_command='SELECT * FROM customers'
customer = c.execute(sql_command)
customer = c.fetchall()
idv4meu8

idv4meu81#

我遇到了和你一样的错误,并且设法解决了它。因为你在settings.py中指定了多个数据库,所以你需要这样初始化你的游标:

from django.db import connections
with connections['network_db'].cursor() as cursor: # use the alias of the database specified in settings.py
        cursor.execute("select * from appname_tablename")
        data = cursor.fetchall()

如果在settings.py中只有一个数据库,则初始化游标如下:

from django.db import connection
with connection.cursor() as cursor:
        cursor.execute("select * from appname_tablename")
        data = cursor.fetchall()

可以参考django文档here

相关问题