【问题标题】:incrementing the id after adding an entry in mysqldb在 mysqldb 中添加条目后递增 id
【发布时间】:2012-08-21 01:23:02
【问题描述】:

我正在尝试编写一个添加条目方法,但我可以让 id 的递增工作。它正在影响我拥有的其他方法,因为当我执行删除时,它会删除所有条目而不是删除特定行。请大家帮忙看看。

def addEntry () :

    #define cursor
    c=db.cursor()

    #execute cursor
    id=c.execute("select max(id)+1 from phones")

    # digs deep to get next id
    id = c.fetchall()[0].values()[0]

    #dosql 
    dosql("insert into phones values (%d,'%s','%s')" % (id,nameVar.get(), phoneVar.get()))

【问题讨论】:

    标签: mysql-python


    【解决方案1】:

    在不了解具体问题的情况下,仅查看您发布的代码,我看到了一些东西。

    1. 为什么不使用 MySQL 中的 auto_increment 列作为您要实现的功能的“id”?

    2. 我在检索行时从未见过以下语法:

      id = c.fetchall()[0].values()[0]

    那行对我不起作用,因为 c.fetchall()[0] 返回一个没有 values 方法的元组。由于您知道查询只会返回一行,因此您可以这样做:

    id = c.fetchone()[0]
    
    or
    
    id, = c.fetchone()
    

    3。您没有锁定表格,因此一次多次运行该代码可能不会为您提供您正在寻找的结果,并且您最终可能会得到 2 行的相同 id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 2011-02-07
      • 1970-01-01
      • 2014-08-03
      • 2011-06-17
      相关资源
      最近更新 更多