【问题标题】:SQLite- Insert using foreign key - PythonSQLite - 使用外键插入 - Python
【发布时间】:2020-02-28 07:38:54
【问题描述】:

我基本上遇到语法问题,在任何地方都找不到太多信息。 我有两张桌子。 Category_tb 和 Information_tb。

Category_tb 有 category_name(text) 列。 信息_tb 有title(text)和category_id(INTEGER)

我没有使用外键,我使用的是 Category_tb 的 ROWID。 以下是 SQL 查询。基本上我在使用 Category_tb.ROWID 作为外键将数据插入到 Information_tb 时遇到问题。

title = 'Some title'
categories = 'Crime'
self.curr.execute("""
                    insert into information_tb values (?,?)""",(
                        [title],
                        ["""select ROWID from Category_tb where Category_tb.category_name = [categories] """]
                        ))

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: python sqlite


    【解决方案1】:

    insert 语句的 values 子句应该是列名。它不能包含选择语句。但是,您可以使用 select 语句指定值。

    试试这个:

    self.curr.execute("insert into information_tb (title, category_id) select ?, ROWID from Category_tb where Category_tb.category_name = ?",
          (title, categories))
    

    记得在之后提交以保存更改。

    【讨论】:

    • 不完全是我想要的,但我有一个大概的想法。我想获取与类别匹配的类别的 ROWID,并将该 ID 插入到 information_tb 的 category_id 中。我写了这个查询,但仍然收到错误,请看一下。 self.curr.execute(""" insert into information_tb (title, category_id) Values (?,select ROWID from category where category.category = ?)""" ,(title, categories[0])) 得到错误“sqlite3 .OperationalError:靠近“选择”:语法错误“
    • @ahsanmukhtar 你不需要values (...。请复制我给出的代码。
    • 我收到了这个 SQLite 错误 sqlite3.InterfaceError: Error binding parameter 0 - 可能是不受支持的类型。
    • @ahsanmukhtar 您必须将值括在括号中:(title, categories)。括号很重要。
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多