c0fec0de / anytree

Python tree data library
Apache License 2.0
955 stars 133 forks source link

Iteration over tree an Insert data to SQL database #185

Open okos01 opened 2 years ago

okos01 commented 2 years ago

Hi! It's interesting how some people deal with Inserting data from nodes to SQL database. If you have some code example, can you share it here?

c0fec0de commented 1 year ago

Please provide a minimal example and re-open the ticket.

okos01 commented 1 year ago

So in my case, I iterate through nodes, and insert data from node to DB. Here is example for one of nodes:

# From nodes to DB
for iter_node in PreOrderIter(root):
    # Transfer data to class_base table
        if iter_node.name == class_base_id
            check_class_base = f"SELECT TOP 1 * FROM class_base WHERE id = '{class_base_id}'"
            cursor.execute(check_class_base)
            check_class_base = cursor.fetchone()
            if check_class_base is not None:
                update_class_base = f"UPDATE vib_class_base SET id = id, class_number = class_number, class_name = class_name WHERE id = '{class_base_id}'"
                cursor.execute(update_class_base)
                connection.commit_db()
            else:
                add_class_base = f"INSERT INTO class_base (id, class_number, class_name) VALUES ('{iter_node.name}', {iter_node.class_number}, '{iter_node.class_name}')"
                cursor.execute(add_class_base)
                connection.commit_db()
    except pyodbc.Error as ex:
        connection.close()
        stacktrace = ex.args[1]
        print('Error while inserting values to table "class_base":\n' + stacktrace)
okos01 commented 1 year ago

P.S. I cannot re-open my own issues if a repo collaborator closed it :)

c0fec0de commented 1 year ago

Can you extend your example code please with a proper database initialization and some example data.

We could add it to https://anytree.readthedocs.io/en/latest/tricks.html. Feel free to add your code here or file a pull request.