I’ve seen two approaches which I’m going to post in the comments to see which one is considered best. Feel free to suggest others.

    • coffeewithalex@lemmy.world
      link
      fedilink
      arrow-up
      8
      ·
      1 year ago

      This, but, with DatabaseConnection being a singleton, and preventing multiple enter clauses.

      You can ensure it’s a singleton by modifying how a new object is built, by overriding the new dunder method. If an instance exists, return that, otherwise create a new one.

    • elguaxo@lemmy.dbzer0.com
      link
      fedilink
      arrow-up
      3
      ·
      1 year ago

      I’ve always liked SQL, so I avoided ORMs for a long time… They are great for so many reasons! I definitely recommend you ORMs, specially the ones that also help you with migrations.

  • const void*@lemmy.world
    link
    fedilink
    arrow-up
    3
    ·
    1 year ago

    Depends on the use case; the question is, do you need to construct and destroy the connection inside each method, or can you do it once, at the start of the program, and exit at the end?

    db = Db(DB_FILE)
    
    post_id = insert_post(db,"hello")
    comment_id = insert_comment(db,post_id)
    
    db.close()