为什么我不能使用变量(使用“%s”或“?”)来引用sqlite的“create table if not exists”和“insert into values”中的表和列名?

lsmd5eda  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(284)

我正在为我的应用程序创建一个数据库类,因为我在各种场合都需要数据库表。我使用的是sqlite3,我需要我的代码尽可能通用,但是当我使用“%s”和/或“?”作为表名和列标题时,我得到了上面提到的错误。
这是我的密码:

import sqlite3

conn = sqlite3.connect("cows.db")
c = conn.cursor()

class databases:
    global c

    def __init__(self, table_name):
        self.table_name = table_name

    def create_table(self, *args,**kwargs):
        c.execute('CREATE TABLE IF NOT EXISTS %s(%s)', (self.table_name, args))
        c.execute("INSERT INTO %s VALUES (%s)", (self.table_name, kwargs))
        conn.commit()

    def delete_record(self, *args):
        c.execute(''' DELETE FROM ? WHERE ? = ?''', (self.table_name, args))
        conn.commit()

cows = databases('cow')
cows.create_table('cow_id REAL', 'lactation_phase TEXT', 'milk_production REAL', 'weight REAL')

错误信息如下:

C:\Users\farid\PycharmProjects\cownutritionmanagmentsystem\venv\Scripts\python.exe C:/Users/farid/PycharmProjects/cownutritionmanagmentsystem/database.py
Traceback (most recent call last):
  File "C:/Users/farid/PycharmProjects/cownutritionmanagmentsystem/database.py", line 24, in <module>
    cows.create_table('cow_id REAL', 'lactation_phase TEXT', 'milk_production REAL', 'weight REAL')
  File "C:/Users/farid/PycharmProjects/cownutritionmanagmentsystem/database.py", line 14, in create_table
    c.execute('CREATE TABLE IF NOT EXISTS %s(%s)', (self.table_name, args))
sqlite3.OperationalError: near "%": syntax error
mgdq6dx1

mgdq6dx11#

你可以用 %s 引用字符串中的表名或其他变量。注意 %s 插入字符串的标记,以及 %d 插入整数的标记。
或者,也可以使用 format 方法替换字符串中变量的值。在 format 方法时,大括号将显示插入值的位置。您可以使用此方法插入多个值,并且值不必只是字符串,但可以是数字和其他python对象。

import sqlite3

conn = sqlite3.connect("cows.db")
c = conn.cursor()

class databases:
    global c

    def __init__(self, table_name):
        self.table_name = table_name

    def create_table(self, *args,**kwargs):
        c.execute('CREATE TABLE IF NOT EXISTS %s(%s)' % (self.table_name, args))
        c.execute("INSERT INTO %s VALUES (%s)" % (self.table_name, kwargs)) # Notice how we have used % operator here
        conn.commit()

    def delete_record(self, *args):
        c.execute(''' DELETE FROM {} WHERE {} = {}'''.format(self.table_name, args)) # We have used format method here
        conn.commit()

cows = databases('cow')
cows.create_table('cow_id REAL', 'lactation_phase TEXT', 'milk_production REAL', 'weight REAL')

相关问题