python - 寻找在 Sqlite3 中创建引用代码的更好方法

标签 python sqlite

我需要为Sqlite3中的表创建引用代码。

它们将遵循“P-1000”格式,并在添加每个新项目时递增 1。

我有以下代码来查找最后一个引用代码并递增它。有没有更简单或更容易的方法来处理这样的自定义标识符?

我不知道 Sqlite3 或其他查询语言是否内置了处理此类事情的方法。

def find_last_reference_code(self):
    query = QueryBuilder(self.table) \
        .select(['reference_code as last_reference_code']) \
        .from_() \
        .where('id = (select max(id) from projects)')
    self.execute(**query.build())
    return self.get_one()

def make_next_reference_code(self):
    last_project = self.find_last_reference_code()
    last_reference_code = last_project["last_reference_code"] if last_project else 'P-1000'
    reference_code = 'P-' + str(int(last_reference_code[2:]) + 1)
    return reference_code

不用担心 QueryBuilder 的东西,它只是我围绕 SQL 查询编写的一个包装器,但如果它在这里有帮助的话,那就是它的工作原理:https://github.com/sarcoma/Invoicing/tree/master/invoicing/query_builder

最佳答案

我建议添加一个类似于以下内容的插入触发器:

  create trigger insert_refcode after insert on Table_name
  begin
     update Table_name
     set reference_code = printf('P-%04d', id+999)
     where rowid=new.rowid;
  end

关于python - 寻找在 Sqlite3 中创建引用代码的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51680083/

相关文章:

android - 从 txt 填充数据库的替代方法

sql-server - 如何将结果添加到声明的变量中

python - 格式化输出数据

python - 将参数从 python 解析为 C++

python - from __future__ import ... 可以保证 Python 2 和 3 的兼容性吗?

javascript - 从sequelize模型 'define'向sqlite添加约束

java - Room 不存储数据

python - Pandas 在字典列表中分组

python通过套接字发送不完整的数据

java - SQLite 和 JDBC : returns UnsatisfiedLinkError