Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iteration over tree an Insert data to SQL database #185

Open
okos01 opened this issue Feb 1, 2022 · 4 comments
Open

Iteration over tree an Insert data to SQL database #185

okos01 opened this issue Feb 1, 2022 · 4 comments

Comments

@okos01
Copy link

okos01 commented Feb 1, 2022

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
Copy link
Owner

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

@okos01
Copy link
Author

okos01 commented Oct 12, 2023

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
Copy link
Author

okos01 commented Oct 12, 2023

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

@c0fec0de c0fec0de reopened this Oct 12, 2023
@c0fec0de
Copy link
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants