sqlite 如何将表名作为变量插入到查询中?

bvjveswy  于 2022-11-24  发布在  SQLite
关注(0)|答案(1)|浏览(172)

我试图通过查询从数据库中选择一个表。我创建了一个表名列表并将其导出到列表中,将必要的列表字段保存为变量,然后将这些变量插入到数据库查询中以导出数据。我最初不知道表名,但通过逻辑找到它并将其写入变量。它给我一个错误:

uch = "_uch"
kam = "_kamera"
pot = "_uzvvod"

conn = sqlite3.connect("kotelnaya.sqlite")
table = pd.read_sql_query("SELECT name FROM sqlite_master WHERE type='table'", conn)

l = len(table)
m = [0] * l
i = 0
k = 1
for k in range(l):
    m[i] = table.at[i, "name"]
    i = i + 1

for num in m:
    if uch in str(num):
        stroka_uch = num

for num in m:
    if kam in str(num):
        stroka_kam = num

for num in m:
    if pot in str(num):
        stroka_pot = num

table = pd.read_sql_query("SELECT * FROM {}".format(stroka_uch), conn)

错误:

cur.execute(*args, **kwargs)
sqlite3.OperationalError: near "7": syntax error

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Z_Python_TGRaschet\venv\database_from_to.py", line 70, in <module>
    table = pd.read_sql_query("SELECT * FROM {}".format(stroka_uch), conn)
  File "C:\Z_Python_TGRaschet\venv\lib\site-packages\pandas\io\sql.py", line 397, in read_sql_query
    return pandas_sql.read_query(
  File "C:\Z_Python_TGRaschet\venv\lib\site-packages\pandas\io\sql.py", line 2078, in read_query
    cursor = self.execute(*args)
  File "C:\Z_Python_TGRaschet\venv\lib\site-packages\pandas\io\sql.py", line 2030, in execute
    raise ex from exc
pandas.errors.DatabaseError: Execution failed on sql 'SELECT * FROM Datatable 7 Test 2_uch': near "7": syntax error
jei2mxaa

jei2mxaa1#

我想这是最简单的解决方案:如果pd.read。

相关问题