繁体   English   中英

为什么我不能使用变量(使用“%s”或“?”)来引用 sqlite 的“CREATE TABLE IF NOT EXISTS”和“INSERT INTO VALUES”中的表名和列名?

[英]Why can't I use variables (using “%s” or “?”) to refer to table and column names in sqlite's “CREATE TABLE IF NOT EXISTS” and “INSERT INTO VALUES”?

我正在为我的应用程序创建一个数据库 class,因为我在各种场合都需要数据库表。 我正在使用 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

您可以使用%s来引用字符串中的表名或其他变量。 注意%s标记插入字符串, %d标记插入 integer。

或者,您也可以使用format方法替换字符串中变量的值。 format方法中,花括号显示插入值应在 go 的位置。 您可以使用此方法插入多个值,值不必只是字符串,也可以是数字和其他 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM